如何观看与AngularJS控制器服务原语的变量? [英] How to watch a primitive service variable in controller with AngularJS?

查看:130
本文介绍了如何观看与AngularJS控制器服务原语的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用$注意它。在$表身在页面初始化射击(含newvalue中未定义),并在btnChangeIsLoggedIn点击不点火。

I'm trying to use $watch for it. The $watch body firing at page initialization (with undefined in newValue) and not firing at "btnChangeIsLoggedIn" click.

<!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>

我在做什么错了?

What I'm doing wrong?

我的code。在的jsfiddle:
http://jsfiddle.net/googman/RA2j7/

推荐答案

您可以传递,将返回该服务的方法的值的函数。角,然后将其比作previous值。

You can pass a function that will return the value of the Service's method. Angular will then compare it to the previous value.

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

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

请注意:文本字段值不更新的原因是因为该按钮仅改变了服务的价值,而不是 $范围的你也可以摆脱初始警报(改变功能的运行),但比较为newValue 来的属性oldValue,只有执行的语句,如果它们是不同的。

Note: the reason the text field value doesn't update is because the button only changes the service's value, not the $scope's You can also get rid of that initial alert (running of the change function) but comparing the newValue to the oldValue and only executing the statements if they are different.

这篇关于如何观看与AngularJS控制器服务原语的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆