Why does the link function of my directive never get called?

徘徊边缘 提交于 2019-12-04 10:19:33
Eduard Gamonal

The error might be somewhere else. I tried it in a jsfiddle and the first version works.

eval()

In any case, you might have a missunderstanding about what $scope.$eval() does:

$scope.$eval() evaluates angularjs code against a scope. JavaScript's eval() function to run arbitrary js code in angularjs is $window.eval(). More about this here: Angular.js: How does $eval work and why is it different from vanilla eval?

I tested the directive isolated from the controller:

<div data-ng-element-ready="console.log('COMPILED!')"></div>

and the directive:

app.directive('ngElementReady', ['$window', function($window) {
return {
    restrict: "A",
    link: function($scope, $element, $attributes) {
        console.log("Reached the link fn", $attributes);
        $window.eval($attributes.ngElementReady);
    }
};
}]);

I do get the value "reached the link fn" and $attributes is correct:

Reached the link fn Object { $$element={...}, $attr={...},  
ngElementReady="console.log('COMPILED!')", more...}

And $window.eval() returns COMPILED!

and here with a controller.

in any case, using eval() to execute code written in an attribute looks dangerous. Anybody can modify the DOM to run code there. At least make sure that it won't affect any other users or server-side.

Reproducing the problem with ng-if

Edited after first comment: I tried making the ng-if expression evaluate to false here This time it doesn't show the message. This probably happens because in order to evaluate ng-if, yuo must compile first the directive. otherwise, it's just code that anuglarjs isn't aware of. However, because it is removed from the DOM, it never reaches the link function.

Execution order of AngularJS functions

In general, the order of execution goes like this (Josh David Miller explains it:

<div directive1>
  <div directive2>
    <!-- ... -->
  </div>
</div>

Now AngularJS will create the directives by running directive functions in a certain order:

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