[英]Angular Directive Load Order
我正在學習Thinkster的指令,當我實際加載index.html時,將鼠標懸停在“Say Something”上,在控制台中我得到:
[“你好”,“你好”,“你好”] ---
我期待[“hello”,“howdy”,“hi”] ---假設指令從左到右進行評估,所以第一個hello被推入$ scope.words,然后是howdy,那么嗨,但是那個很清楚不是這里發生的事情,引擎蓋下面究竟發生了什么?
角度代碼:
(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>
指令有一個名為'priority'的字段,用於設置編譯順序。 默認優先級為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
優先
當在單個DOM元素上定義了多個指令時,有時需要指定應用指令的順序。 優先級用於在調用編譯函數之前對指令進行排序。 優先級定義為數字。 首先編譯具有更高數字優先級的指令。 預鏈接功能也按優先級順序運行,但后鏈接功能以相反的順序運行。 具有相同優先級的指令的順序是未定義的。 默認優先級為0。
更新
如果優先級相等,則按字母順序編譯指令,然后反向調用鏈接(post-link)函數。
請參考此了解詳情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.