指令链接函数中的 scope.$watch 未被调用 [英] scope.$watch in directive link function not getting called
本文介绍了指令链接函数中的 scope.$watch 未被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这家工厂,
.factory('authentication', [function() {
return {
loginRequired: false
};
}]);
我有这个控制器,
.controller('TopNavCtrl', ['$scope', 'authentication', function($scope, authentication) {
$scope.login = function() {
authentication.loginRequired = true;
};
}]);
我在指令中有这个链接函数,
and I have this link function in a directive,
link: function(scope, element, attrs) {
scope.show = false;
scope.$watch(authentication.loginRequired, function(value) {
scope.show = value;
});
}
当 authentication.loginRequired = true;
在控制器中完成时,指令中的 scope.$watch
不会被调用.
When authentication.loginRequired = true;
is done in the controller, the scope.$watch
in the directive isn't called.
知道为什么吗?
推荐答案
Scope.$watch 接受作为第一个参数表达式或函数.您作为第一个参数传递的是存储在 authetication.loginRequired
中的 值.
Scope.$watch accepts as first parameter expression or function. What you are passing as first parameter is a value stored in authetication.loginRequired
.
以下将起作用(假设您已正确注入 authetication
工厂):
Following will work (assuming you have correctly injected authetication
factory):
link: function(scope, element, attrs) {
scope.show = false;
scope.$watch(function(){return authentication.loginRequired;}, function(value) {
scope.show = value;
});
}
这篇关于指令链接函数中的 scope.$watch 未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文