javascript 了解指令优先级如何在 Angularjs 中工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33180437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding how directive priority level work in Angularjs
提问by user4904589
app.js
is:
app.js
是:
var app = angular.module('myApp',[]);
app.directive('myDirective2', function () {
return{
restrict: 'A',
priority: 100,
//template:"<h1>myDirective2</h1>",
controller: function ($scope, $element, $transclude,$timeout) {
//$scope.name = "executed myDirective2";
$timeout(function () {
$scope.name = "executed myDirective2";
}, 3000);
}
};
});
app.directive('myDirective3', function () {
return{
restrict: 'A',
priority: 200,
//template:"<h1>myDirective3</h1>",
controller: function ($scope, $element, $transclude, $timeout) {
$timeout(function () {
$scope.name = "executed myDirective3";
}, 3000);
}
};
});
And index.html
is:
并且index.html
是:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="js/angular.js" type="text/javascript"></script>
<script src="js/app.js" type="text/javascript"></script>
</head>
<body>
<div my-directive3 my-directive2></div>
<br/>
Name:{{name}}
</body>
</html>
Though priority for my-directive2
is lesser than my-directive3
still why my-directive2
is getting executed? Should not it be the directive with higher priority which in this case is my-directive3
?
虽然优先级my-directive2
低于my-directive3
仍然为什么my-directive2
被执行?在这种情况下,它不应该是具有更高优先级的指令my-directive3
吗?
回答by arg20
Priority is a number for which directive gets executed firstin case of multiple priorities. Basically you use it to determine the order of execution, not to exclude other directives.
优先级是在多个优先级的情况下首先执行指令的数字。基本上你用它来确定执行顺序,而不是排除其他指令。
Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.
首先编译具有更高数字优先级的指令。预链接功能也按优先级顺序运行,但后链接功能以相反的顺序运行。具有相同优先级的指令的顺序是未定义的。默认优先级为 0。
You can read more about it here.
您可以在此处阅读更多相关信息。