如何使用AngularJS在控制器中观察原始服务变量?

Goo*_*man 11 angularjs

我正在尝试使用$ 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>
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

我在JSFiddle的代码: http ://jsfiddle.net/googman/RA2j7/

The*_*One 19

您可以传递一个函数,该函数将返回Service方法的值.然后Angular将它与之前的值进行比较.

$scope.$watch(function(){
    return authService.isLoggedIn;
}, function (newValue) {
    alert("isLoggedIn changed to " + newValue);
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/TheSharpieOne/RA2j7/2/

注意:文本字段值不更新的原因是因为按钮只更改了服务的值,而不是$scope's你也可以去掉那个初始警报(运行更改函数)但是只比较newValueoldValue而且只是如果它们不同,则执行它们.