我正在从 Thinkster 学习指令,当我实际加载 index.html 并将鼠标悬停在“Say Something”上时,在控制台中我得到:
["你好", "嗨", "你好"]---
我期待 ["hello", "howdy", "hi"]--- 假设指令从左到右求值,所以首先 hello 被插入 $scope.words,然后 howdy,然后 hi,但这显然不是这里发生的事情,引擎盖下到底发生了什么?
Angular 代码:
(function() {
'use strict';
angular.module('greetings', [])
.directive("welcome", function() {
return {
restrict: "E",
controller: function($scope) {
$scope.words = [];
this.sayHello = function() {
$scope.words.push("hello");
};
this.sayHowdy = function() {
$scope.words.push("howdy");
};
this.sayHi = function() {
$scope.words.push("hi");
};
},
link: function(scope, element){
element.bind("mouseenter", function() {
console.log(scope.words);
});
}
}
})
.directive("hello", function() {
return {
require: "welcome",
link: function (scope, element, attrs, welcomeCtrl) {
welcomeCtrl.sayHello();
}
};
})
.directive("howdy", function() {
return {
require: "welcome",
link: function (scope, element, attrs, welcomeCtrl) {
welcomeCtrl.sayHowdy();
}
};
})
.directive("hi", function() {
return {
require: "welcome",
link: function (scope, element, attrs, welcomeCtrl) {
welcomeCtrl.sayHi();
}
};
});
})();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Egghead Directive</title>
<link rel="stylesheet" href="styles.css">
</head>
<body ng-app="greetings">
<welcome hello howdy hi>Say something!</welcome>
<!-- Javascripts -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="main.js"></script>
</body>
</html>
最佳答案
指令有一个名为“优先级”的字段,用于设置编译顺序。默认优先级为 0,将它们放在元素上的顺序无关紧要。
.directive("hi", function() {
return {
require: "welcome",
priority: 1,
link: function (scope, element, attrs, welcomeCtrl) {
welcomeCtrl.sayHi();
}
};
});
优先级越大越早编译
来自 https://docs.angularjs.org/api/ng/service/$compile
priority
When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. 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.
更新
如果优先级相等,则指令按字母顺序编译,然后反向调用链接(后链接)函数。
请引用this了解详情。
关于javascript - Angular Directive(指令)加载顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846735/