简体   繁体   English

监视属性的Angular指令

[英]Angular directive that watches a propertie

I like to write a small Angular directive that hide or show an element if the user is logged in. The authentication factory that I inject, basically reads and writes values to a cookie. 我喜欢编写一个小的Angular指令,如果用户登录则隐藏或显示一个元素。我注入的身份验证工厂基本上是将值读写到cookie中。 The problem is, that "scope.$watch(authentication.isAuthenticated" is called just once. If "isAuthenticated" changes, the event/watcher will not be called. 问题是,“ scope。$ watch(authentication.isAuthenticated”仅被调用一次。如果“ isAuthenticated”发生更改,则事件/观察者将不会被调用。

app.directive('IfUserIsLoggedin', ["authentication", function (authentication) {  
return {
    restrict: 'A',
    link: function (scope, element, attrs) {

        function setClass() {
            if (element !== undefined) {
                if (authentication.isAuthenticated) {
                    element.removeClass("hidden");
                } else {
                    element.addClass("hidden");
                }
            }
        }

        scope.$watch(authentication.isAuthenticated, function () {
            setClass();
        });

        setClass();
    }
};}]);

I used this sample from the Angular documention for my code. 将Angular文档中的样本用于我的代码。

The reason your code doesn't wok is because the value you're watching is not on the scope. 您的代码无法正常启动的原因是,您正在查看的值不在范围内。 Either add it to the scope, or use a different form of $watch(...) like so: 可以将其添加到范围中,也可以使用其他形式的$ watch(...),如下所示:

scope.$watch(function() { return authentication.isAuthenticated }, function () {
    setClass();
});

and your code will be happy :). 并且您的代码会很高兴:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM