错误可能在其他地方。我尝试过jsfiddle http://jsfiddle.net/egamonal/S53eA/第一个版本有效。
eval()
无论如何,您可能对什么有误解$scope.$eval()
does:
$scope.$eval()
根据范围评估 angularjs 代码。 JavaScript 的eval()
在 angularjs 中运行任意 js 代码的函数是$window.eval()
。有关此内容的更多信息,请参见此处:Angular.js:$eval 是如何工作的以及为什么它与普通 eval 不同? https://stackoverflow.com/questions/15671471/angular-js-how-does-eval-work-and-why-is-it-different-from-vanilla-eval
我测试了与控制器隔离的指令:
<div data-ng-element-ready="console.log('COMPILED!')"></div>
和指令:
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);
}
};
}]);
我确实得到了“到达链接 fn”的值并且$attributes
是正确的:
Reached the link fn Object { $$element={...}, $attr={...},
ngElementReady="console.log('COMPILED!')", more...}
And $window.eval()
回报COMPILED!
and here http://jsfiddle.net/egamonal/S53eA/1/带控制器。
无论如何,使用eval()
执行在属性中编写的代码看起来很危险。任何人都可以修改 DOM 来运行代码。至少确保它不会影响任何其他用户或服务器端。
使用 ng-if 重现问题
第一条评论后编辑:
我尝试使 ng-if 表达式计算结果为 falsehere http://jsfiddle.net/egamonal/S53eA/2/这次没有显示该消息。
这可能会发生,因为为了评估 ng-if,yuo 必须首先编译该指令。否则,这只是 anuglarjs 不知道的代码。但是,由于它已从 DOM 中删除,因此它永远不会到达链接函数。
AngularJS函数的执行顺序
一般来说,执行顺序是这样的(乔什·大卫·米勒解释道 https://groups.google.com/d/msg/angular/bBgJ6Tb-mHo/PDSU76pNPtAJ:
<div directive1>
<div directive2>
<!-- ... -->
</div>
</div>
现在 AngularJS 将通过按一定顺序运行指令函数来创建指令:
directive1: compile
directive2: compile
directive1: controller
directive1: pre-link
directive2: controller
directive2: pre-link
directive2: post-link
directive1: post-link