【发布时间】:2026-01-21 03:30:02
【问题描述】:
我正在尝试使用 $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/
【问题讨论】:
标签: angularjs