AngularJs绑定指令到getter属性

时间:2013-06-06 15:06:12

标签: data-binding angularjs

您是否可以使用AngularJs将指令绑定到服务上的getter属性?

我有一个试图在服务上查看属性的指令,它会在应用启动时更新一次。然后它永远不会更新,即使被监视的属性更新。

这是我的指示:

authorization.directive("authorization", ["$rootScope", "authenticationService", "authorizationService", function ($rootScope, authenticationService, authorizationService) {
return {
    restrict: "A",
    link: function (scope, element, attrs) {
        var prevDisp = element.css("display");

        function update(user) {
            if (!authorizationService.isAuthorized(attrs.authorization, user)) { element.css("display", "none"); }
            else { element.css("display", prevDisp); }
        }

        scope.$watch(authenticationService.user, function () { update(authenticationService.user); });
    }
};

}]);

以下是我服务的缩减版本:

App.factory("authenticationService", function ($http, $location) {
var _user = { email: null, ...... };

return {
    get user() { return _user; }, //This is the property I am trying to bind too
    login: function () { do stuff },
    logout: function () { do other things }
}

});

2 个答案:

答案 0 :(得分:4)

你要么观察一个实际的函数(那是一个可调用的东西),要么是在作用域的上下文中看到$eval的字符串。不是吸气剂,它只会返回物体。

尝试

scope.$watch(function () { return authenticationService.user; },
             function () { update(authenticationService.user); },
             true); // use true to check for differences in object's properties.

答案 1 :(得分:-1)

$watch传播函数或表达式,并且在表达式的情况下,对当前范围进行评估。如果您要观察变量,请确保它首先附加到范围:

scope.user = authenticationService.user
scope.$watch('user', function (user, old) { update(user); });