Ich bin neu zu angularjs und ich bin mit diesem seltsamen Problem konfrontiert, wo $ watch nicht auf Änderung einer Variablen im Dienst feuern wird. Ich weiß nicht, wo ich einen Fehler gemacht habe.
Plunkr: Link to Plunkr
script.js Datei:
var app = angular.module("app", []);
app.factory("loggedInUser", [loggedInUser]);
function loggedInUser() {
var currentLoggedInUser = undefined;
setTimeout(function() {
currentLoggedInUser = "Karthik";
console.log("Updated user name");
}, 3000);
return {
getLoggedInUser: function() {
return currentLoggedInUser;
}
};
}
app.controller("ctrl", ["$scope", "loggedInUser", ctrl]);
function ctrl($scope, loggedInUser) {
var vm = this;
$scope.$watch(function() {
return loggedInUser.getLoggedInUser();
}, function() {
vm.loggedInUserName = loggedInUser.getLoggedInUser();
console.log("Inside Watch");
},true);
}
HTML:
<html>
<head>
<script src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js" data-require="[email protected]" data-semver="1.5.8"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<h1 ng-controller="ctrl as vm">
Hello <span ng-bind="vm.loggedInUserName"></span>
</h1>
</body>
</html>
Was schaust du? Sie müssen es eine Variable geben, um tatsächlich zu sehen ... Ie, $ scope. $ Watch ('some.variable', (alt-val, neu-val) => {do_something();} – rrd
@rrd Ich beobachte für Änderungen in der Variable 'currentLoggedInUser' – Karthik
Ich habe gerade eine Frage wie diese beantwortet, hier http://stackoverflow.com/a/41693955/1061668 –