萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

AngularJS 自定義指令深度解析:從 Element 到 Compile/Link 生命週期

指令類型與激活方式

AngularJS 指令擴展 HTML 語義,支援四種匹配模式(restrict):

  • E (Element):<student></student>
  • A (Attribute):<div student></div>
  • C (Class):<div class="student"></div>
  • M (Comment):<!-- 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 vs Link 關鍵差異

階段執行時機執行次數典型用途
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 };
}]);

渲染結果:兩張帶邊框、粉紅背景的學生卡片,數據來自控制器作用域。

進階技巧

  • transclude: true 保留原始內容插槽。
  • controller 公開 API 供其他指令 require。
  • bindToController 配合 controllerAs 簡化作用域綁定。
copyright © 萬盛學電腦網 all rights reserved