我是angularjs的新手,我正面临着这样一个奇怪的问题:$ watch在服务变量中没有触发。我不知道我在哪里弄错了。
Plunkr:Link to Plunkr
script.js文件:
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="angularjs@1.5.8" 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>
答案 0 :(得分:1)
使用$ timeout而不是setTimeout? ..因为它需要$ scope。$ apply(在角度事件之外).. $ timeout是setTimeout的角度包装..类似于:
// Code goes here
var app = angular.module("app", []);
app.factory("loggedInUser", ["$timeout", loggedInUser]);
function loggedInUser($timeout) {
var currentLoggedInUser;
$timeout(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);
}
但是..如果你想使用SetTimeout函数:
// Code goes here
var app = angular.module("app", []);
app.factory("loggedInUser", ["$rootScope",loggedInUser]);
function loggedInUser($rootScope) {
var currentLoggedInUser = undefined;
setTimeout(function() {
$rootScope.$apply(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);
}