我正在尝试使用 $watch 。 $watch 主体在页面初始化时触发(在 newValue 中未定义),而不是在单击“btnChangeIsLoggedIn”时触发。
<!DOCTYPE html>
<html data-ng-app="myApp">
<head><title>title</title></head>
<body>
<script src="lib/angular/angular.js"></script>
<div ng-controller="ctrl1">
<input type="text" ng-model="isLoggedIn" />
<input type="button" id="btnChangeIsLoggedIn"
value="change logged in" ng-click="change()" />
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.service('authService', function () {
this.isLoggedIn = false;
});
myApp.controller('ctrl1', function ($scope, authService) {
$scope.isLoggedIn = authService.isLoggedIn;
$scope.$watch("authService.isLoggedIn", function (newValue) {
alert("isLoggedIn changed to " + newValue);
}, true);
$scope.change = function() {
authService.isLoggedIn = true;
};
});
</script>
</body>
</html>
我做错了什么?
我在 JSFiddle 的代码:
http://jsfiddle.net/googman/RA2j7/
最佳答案
您可以传递一个函数,该函数将返回服务方法的值。然后 Angular 会将它与之前的值进行比较。
$scope.$watch(function(){
return authService.isLoggedIn;
}, function (newValue) {
alert("isLoggedIn changed to " + newValue);
});
演示:http://jsfiddle.net/TheSharpieOne/RA2j7/2/
注意:文本字段值没有更新的原因是因为按钮只更改了服务的值,而不是
$scope
的你也可以摆脱那个初始警报(运行更改功能),但比较 newValue
到 oldValue 并且仅在它们不同时才执行语句。
关于angularjs - 如何使用 AngularJS 观察 Controller 中的原始服务变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21100004/