AngularJS 自訂指令讓你將可重用的 DOM 行為封裝為聲明式 HTML 標籤/屬性/類別/註釋。本文系統介紹四種類型,並以實際專案重構「評論區塊」為例,示範從切割模板到註冊指令的完整流程。
| 類型 | restrict 值 | 使用方式 | 適用場景 |
|---|---|---|---|
| 元素指令 | E | <guitar-reviews></guitar-reviews> | 獨立 UI 元件(卡片、模態框、圖表) |
| 屬性指令 | A | <div guitar-reviews></div> | 行為擴充(驗證、提示、拖曳) |
| CSS 類別指令 | C | <div class="guitar-reviews"></div> | 樣式相關行為(不建議常用) |
| 註釋指令 | M | <!-- directive:guitar-reviews --> | 極少見,特殊模板引擎整合 |
官方建議優先使用 E(元素) 與 A(屬性),語意最清晰。
app.directive('guitarReviews', function() {
return {
restrict: 'E', // 或 'A', 'EA', 'EAC' 等組合
templateUrl: 'custom-directives/reviews.html', // 外部模板
// template: '...', // 內聯模板(簡單情況)
// scope: {}, // 隔離作用域
// controller: function() {}, // 指令專用控制器
// link: function(scope, elem, attrs) {} // DOM 操作邏輯
};
});
命名慣例:HTML 使用連字號 guitar-reviews,JS 定義駝峰 guitarReviews,Angular 自動轉換。
實戰重構:將評論區塊抽離為 <user-reviews> 元素指令
步驟 1:建立模板檔案 partials/cDirectives/reviews.html
<!-- Review Tab START -->
<div ng-show="panel.isSelected(3)" class="reviewContainer" ng-controller="ReviewController as reviewCtrl">
<div class="longDescription uReview" ng-repeat="review in guitarVariable[whichGuitar].reviews">
<h3>Review Points: {{review.star}}</h3>
<p>{{review.body}} ~{{review.name}} on <date>{{review.createdOn | date:'MM/yy'}}</date></p>
</div>
<div ng-show="add === 1" class="longDescription uReview">
<h3>Review Points: {{reviewCtrl.review.star}} <span ng-click="add=0">X</span></h3>
<p>{{reviewCtrl.review.body}} ~ {{reviewCtrl.review.name}}</p>
</div>
<a href ng-click="add=1" class="addReviewLink">Add review</a>
<form class="reviewForm" name="reviewForm" ng-submit="reviewForm.$valid && reviewCtrl.addReview(guitarVariable.indexOf(guitarVariable[whichGuitar]))" novalidate ng-show="add===1">
<div>
Review Points: <select ng-model="reviewCtrl.review.star" ng-options="point for point in [5,4,3,2,1]" required></select>
Email: <input type="email" ng-model="reviewCtrl.review.name" required>
<button type="submit">Submit</button>
</div>
<textarea placeholder="Enter your experience..." ng-model="reviewCtrl.review.body"></textarea>
</form>
</div><!-- END Review Tab -->
步驟 2:原頁面替換為指令標籤
<user-reviews></user-reviews>
步驟 3:註冊指令
GuitarControllers.directive('userReviews', function() {
return {
restrict: 'E',
templateUrl: 'partials/cDirectives/reviews.html'
};
});
進階擴充:隔離作用域與雙向綁定
若需傳遞資料進指令,定義隔離作用域:
scope: {
guitarData: '=', // 雙向綁定物件
onSave: '&', // 回調函式
title: '@' // 字串屬性
}
使用時:<user-reviews guitar-data="currentGuitar" on-save="saveReview()" title="用戶評價"></user-reviews>
檔案結構建議
app/
directives/
userReviews/
userReviews.js // 指令定義
userReviews.html // 模板
userReviews.css // 樣式(可選)
userReviews.spec.js // 測試
將模板、樣式、邏輯共置於同一目錄,符合元件化開發趨勢,便於遷移至 Angular (2+) 元件架構。

