AngularJS 可以允許自行定義新的 directive
能以四種不同型態使用 element, attribute, class, comment
其中 attribute, class 方式,可以在同一個 element 上宣告多個 directive
每個 directive 又有各自的 scope 屬性設定
乍看之下好像 directive scope 似乎是獨立的
但是事實上~~
同一個 element 上宣告多個 directive
無論怎樣設定 scope 屬性皆共用同一個 $scope
差別僅在於:
- 皆共用 parent scope (scope: false)
- 皆共用 new scope (scope: true)
- 皆共用 isolate scope (scope: {})
多組 scope 設定優先順序:isolate scope > new scope > parent scope
也因此,directive priority 處理順序也有一些限制在
要求建立 isolate scope 之後不可以再出現要求 isolate scope 或是 new scope
否則會得到
Error: Multiple directives [xxx, xxx] asking for isolated scope on: ...
以下是簡單的測試程式:
<!DOCTYPE HTML>
<html ng-app id="ng-app">
<head>
<meta charset="UTF-8">
<title>AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script>
var app = angular.module("ng");
var genNgDir = function(name, priority, scope) {
app.directive(name, function factory() {
return {
priority: priority,
scope: scope,
controller: function($scope) {
console.log(name, $scope);
}
};
});
};
genNgDir("myDir01", 0, {});
genNgDir("myDir02", 1, true);
genNgDir("myDir03", 2, false);
</script>
</head>
<body>
<p my-dir01 my-dir02 my-dir03>Content</p>
</body>
</html>
Read more...



