scope.$watch in directive link function not getting called

南笙酒味 提交于 2019-12-10 03:46:44

问题


I have this factory,

.factory('authentication', [function() {

    return {
      loginRequired: false
    };
  }]);

I have this controller,

.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;
    });
  }

When authentication.loginRequired = true; is done in the controller, the scope.$watch in the directive isn't called.

Any ideas why?


回答1:


Scope.$watch accepts as first parameter expression or function. What you are passing as first parameter is a value stored in authetication.loginRequired.

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;
    });
  }



回答2:


Following up @jusio's answer, it's also possible to use a string expression as long as you make your factory part of the scope:

scope.authentication = authentication;
scope.$watch('authentication.loginRequired', function(value) {
...
});

That's so because when a $watch is provided with a string expression, it evaluates that string against its scope.

You should decide whether it's worth cluttering your directive's scope so you can have an arguably more readable code. If you're already doing it for another reason, then it's no big deal.



来源:https://stackoverflow.com/questions/19281230/scope-watch-in-directive-link-function-not-getting-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!