我喜欢编写一个小的 Angular 指令,在用户登录时隐藏或显示一个元素。我注入(inject)的身份验证工厂基本上读取值并将其写入 cookie。 问题是,“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();
}
};}]);
我用过this sample from the Angular documention对于我的代码。
最佳答案
您的代码无法正常运行的原因是您正在查看的值不在范围内。要么将其添加到作用域,要么使用不同形式的 $watch(...) ,如下所示:
scope.$watch(function() { return authentication.isAuthenticated }, function () {
setClass();
});
你的代码会很高兴:)。
关于javascript - 观察属性的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26217180/