angularjs - 如何使用 AngularJS 观察 Controller 中的原始服务变量?

标签 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>

我做错了什么?

我在 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/

相关文章:

Angularjs使用Facebook认证策略不拦截nodejs服务器提供的token

javascript - google chart a.S 不是函数

angularjs - Karma 单元测试中未解决 Angular $q.when

angularjs - 使用 sinon、mocha、chai 进行 Angular 测试

javascript - AngularJS 输入自动对焦

angularjs - 将 ui-router 与 Bootstrap-ui 模态一起使用

angularjs - AngularFire:如何将部分更新(单个字段)应用于 $firebaseArray 中的项目?

javascript - 智能表转到所选项目

python - 使用 JSON 将数据从 Angular.js POST 到 Django REST API

angularjs - express 4 : How do I send JSON object to view?