AngularJS 指令擴展 HTML 語義,支援四種匹配模式(restrict):
<student></student><div student></div><div class="student"></div><!-- directive:student -->app.directive('student', function() {
return {
restrict: 'E', // 僅作為元素激活
scope: { student: '=name' }, // 隔離作用域,雙向綁定 name 屬性
template: 'Student: <b>{{student.name}}</b>, Roll: <b>{{student.rollno}}</b>',
compile: function(element, attrs) {
// 編譯階段:DOM 結構操作、共享邏輯(僅執行一次)
element.css('border', '1px solid #ccc');
return function link(scope, element, attrs) {
// 連結階段:實例化作用域、綁定事件、每個實例執行
element.html('Student: <b>' + scope.student.name + '</b>...');
element.css('background-color', '#ff00ff');
};
}
};
});
| 階段 | 執行時機 | 執行次數 | 典型用途 |
|---|---|---|---|
| Compile | 模板編譯階段(頁面載入) | 每個指令**一次** | DOM 結構轉換、共享事件綁定、性能優化 |
| Link | 實例連結階段(每個指令實例) | 每個實例**一次** | 作用域綁定、監聽器註冊、實例級 DOM 操作 |
原則:能在 compile 做的不放到 link;需訪問實例作用域才用 link。
= / =attr:雙向綁定父作用域屬性@ / @attr:單向綁定字串(插值表達式)& / &attr:執行父作用域函數表達式範例中 scope: { student: '=name' } 使指令內 student 與父作用域 name 指向同一對象。
<div ng-app="mainApp" ng-controller="StudentController">
<student name="Mahesh"></student><br/>
<student name="Piyush"></student>
</div>
app.controller('StudentController', ['$scope', function($scope) {
$scope.Mahesh = { name: 'Mahesh Parashar', rollno: 1 };
$scope.Piyush = { name: 'Piyush Parashar', rollno: 2 };
}]);
渲染結果:兩張帶邊框、粉紅背景的學生卡片,數據來自控制器作用域。
require。controllerAs 簡化作用域綁定。