精心設計的指令能封裝重複性 DOM 操作,提升開發效率與使用者體驗。本文介紹三個高頻實用指令的完整實作。
輸入 Email 自動計算 MD5 雜湊並生成 Gravatar URL,支援尺寸與預設圖參數:
app.directive('gravatarImage', function() {
return {
restrict: 'AE',
replace: true,
scope: { email: '@', size: '@' },
template: '<img ng-src="https://www.gravatar.com/avatar/{{hash}}?s={{size}}&d=identicon" />',
link: function(scope, element, attrs) {
attrs.$observe('email', function(value) {
if (!value) return;
scope.hash = md5(value.toLowerCase()); // 內建 MD5 實作或引入函式庫
scope.size = scope.size || 60;
});
}
};
});
// 使用:
當綁定表達式為真時,延遲一幀聚焦目標元素,解決動態顯示輸入框無法聚焦問題:
app.directive('focusMe', ['$timeout', function($timeout) {
return {
scope: { trigger: '@focusMe' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if (value === "true") {
$timeout(function() { element[0].focus(); }, 0);
}
});
}
};
}]);
// 使用:
// 新增
//
攔截 $http 請求週期,自動顯示/隱藏載入動畫:
app.directive('loadingIndicator', ['$http', function($http) {
return {
restrict: 'AE',
template: '<div class="loading" ng-show="isLoading"><span class="spinner"></span>載入中...</div>',
link: function(scope) {
scope.isLoading = false;
var pending = 0;
scope.$watch(function() { return $http.pendingRequests.length; }, function(len) {
scope.isLoading = len > 0;
});
}
};
}]);
// 使用: 置於版面頂部或表單區塊
scope: {} 避免污染父作用域$timeout 確保 DOM 就緒,attrs.$observe 監聽屬性變化將這些指令納入專案共用模組,即可在所有頁面以聲明式方式複用,大幅減少控制器中的 DOM 操作代碼。