萬盛學電腦網

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

AngularJS ngShow/ngHide 指令深度解析:布爾值、表達式、函數三種模式控制元素顯示隱藏

指令核心機制

ng-show / ng-hide 通過添加/移除 .ng-hide CSS 類控制元素可見性:

.ng-hide { display: none !important; }
  • ng-show="expr":expr 為真 → 移除 .ng-hide(顯示);為假 → 添加 .ng-hide(隱藏)
  • ng-hide="expr":邏輯相反

本質是 display: none 切換,元素仍在 DOM 中,佔據佈局空間(可配合 visibility: hidden 或 position: absolute 調整)。

三種使用模式詳解

1. 布爾值模式(最簡單)

<!-- Controller: $scope.isLoggedIn = true; -->
<div ng-show="isLoggedIn">歡迎回來!</div>
<div ng-hide="isLoggedIn">請先登錄</div>

<!-- 取反 -->
<div ng-show="!isLoggedIn">遊客模式</div>

2. 表達式模式(比較運算)

<!-- Controller: $scope.user = { role: 'admin', status: 1 }; -->
<div ng-show="user.role === 'admin'">管理員面板</div>
<div ng-show="user.status === 1">賬號正常</div>
<div ng-show="items.length > 0">有數據</div>
<div ng-hide="loading">內容區域</div>

3. 函數模式(複雜邏輯封裝)

<div ng-show="hasPermission('delete')"><button>刪除</button></div>


$scope.hasPermission = function(action) {
  return $scope.user.permissions.indexOf(action) !== -1;
};

// 或者 ng-hide 配合取反函數
<div ng-hide="isDisabled('save')"><button>保存</button></div>
$scope.isDisabled = function(btn) {
  return !$scope.form.$valid || $scope.submitting;
};

實戰案例:動態表單字段顯示/隱藏

<form name="profileForm" ng-controller="ProfileCtrl">
  <div class="form-group">
    <label>用戶類型</label>
    <select ng-model="profile.type" class="form-control">
      <option value="personal">個人</option>
      <option value="company">企業</option>
    </select>
  </div>
  
  <!-- 個人用戶字段 -->
  <div ng-show="profile.type === 'personal'" class="form-group">
    <label>身份證號</label>
    <input type="text" ng-model="profile.idCard" class="form-control" required>
  </div>
  
  <!-- 企業用戶字段 -->
  <div ng-show="profile.type === 'company'" class="form-group">
    <label>營業執照號</label>
    <input type="text" ng-model="profile.license" class="form-control" required>
    <label>法人姓名</label>
    <input type="text" ng-model="profile.legalPerson" class="form-control" required>
  </div>
  
  <button ng-disabled="profileForm.$invalid">保存</button>
</form>

ng-show/ng-hide vs ng-if 關鍵區別

特性ng-show/ng-hideng-if
DOM 狀態始終存在,切換 display條件假時從 DOM 移除,真時重建
作用域繼承共享父作用域創建子作用域(原型繼承)
性能初始渲染快,切換快;大量隱藏元素佔內存初始渲染慢(條件真時),切換慢;節省內存
適用場景頻繁切換、簡單條件、Tab 面板條件較穩定、複雜子結構、權限控制
動畫支持.ng-hide-add/.ng-hide-remove.ng-enter/.ng-leave

動畫增強(ngAnimate)

<!-- 引入 angular-animate.js 並注入 ngAnimate 模塊 -->
<div ng-show="visible" class="animate-show">內容</div>

<style>
.animate-show {
  transition: all 0.3s ease;
  opacity: 1;
  height: auto;
  overflow: hidden;
}
.animate-show.ng-hide-add { opacity: 1; height: auto; }
.animate-show.ng-hide-add.ng-hide-add-active { opacity: 0; height: 0; }
.animate-show.ng-hide-remove { opacity: 0; height: 0; }
.animate-show.ng-hide-remove.ng-hide-remove-active { opacity: 1; height: auto; }
</style>

常見坑與最佳實踐

❌ 坑 1:表達式中使用未定義變量

<div ng-show="user.name">...</div> <!-- user 為 undefined 時拋錯 -->
<div ng-show="user && user.name">...</div> <!-- 安全 -->

❌ 坑 2:ng-show 爭奪顯示權導致閃爍

<div ng-show="a">A</div>
<div ng-show="b">B</div>
<!-- a/b 同時為真時疊加顯示,非互斥 -->
// 互斥邏輯應在 Controller 保證,或用 ng-switch

❌ 坑 3:ng-hide 配合 ! 運算符降低可讀性

<div ng-hide="!isValid">...</div> <!-- 雙重否定 -->
<div ng-show="isValid">...</div> <!-- 正向表達 -->

✅ 最佳實踐

  1. 優先用 ng-show/ng-hide:頻繁切換、Tab、模態框、下拉菜單
  2. 條件穩定/權限控制用 ng-if:避免不必要的 Watcher、減少內存
  3. 複雜條件封裝為函數:模板保持乾淨,邏輯可測試、可復用
  4. 動畫類名統一規範:.animate-fade、.animate-slide 復用
  5. 無障礙:隱藏內容對屏幕閱讀器仍可讀,如需完全隱藏用 ng-if 或 aria-hidden="true"

進階:自定義顯示/隱藏指令

app.directive('myShow', ['$animate', function($animate) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      scope.$watch(attrs.myShow, function(val) {
        $animate[val ? 'removeClass' : 'addClass'](elem, 'ng-hide');
      });
    }
  };
}]);

總結

ng-show/ng-hide 是 AngularJS 控制元素可見性的基礎指令,通過 .ng-hide 類切換 display: none。掌握布爾值、表達式、函數三種綁定模式,理解與 ng-if 的 DOM/作用域/性能差異,配合 ngAnimate 實現平滑過渡,能構建流暢、可維護的交互體驗。核心原則:模板只做聲明式綁定,邏輯下沉到 Controller/Service。

copyright © 萬盛學電腦網 all rights reserved