萬盛學電腦網

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

三大提升 AngularJS 使用者體驗的實用指令:Gravatar、自動聚焦、載入指示器

精心設計的指令能封裝重複性 DOM 操作,提升開發效率與使用者體驗。本文介紹三個高頻實用指令的完整實作。

1. gravatarImage:Gravatar 頭像自動生成

輸入 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;
      });
    }
  };
});

// 使用:

2. focusMe:條件式自動聚焦

當綁定表達式為真時,延遲一幀聚焦目標元素,解決動態顯示輸入框無法聚焦問題:

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);
        }
      });
    }
  };
}]);

// 使用:
// 新增
// 

3. loadingIndicator:全域/區域載入狀態指示器

攔截 $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;
      });
    }
  };
}]);

// 使用: 置於版面頂部或表單區塊

設計原則總結

  • 單一職責: 每個指令專注單一 UX 模式
  • 隔離作用域: 使用 scope: {} 避免污染父作用域
  • 聲明式 API: 透過屬性傳遞配置,HTML 可讀性高
  • 效能考量: 使用 $timeout 確保 DOM 就緒,attrs.$observe 監聽屬性變化

將這些指令納入專案共用模組,即可在所有頁面以聲明式方式複用,大幅減少控制器中的 DOM 操作代碼。

copyright © 萬盛學電腦網 all rights reserved