當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


AngularJS ng-show用法及代碼示例


AngluarJS中的ng-show指令用於顯示或隱藏指定的HTML元素。如果ng-show屬性中的給定表達式為true,則將顯示HTML元素,否則將隱藏HTML元素。所有HTML元素都支持它。

用法:

<element ng-show="expression"> Contents... </element> 

範例1:本示例使用ng-show指令在選中複選框後顯示HTML元素。


<!DOCTYPE html> 
<html> 
  
<head> 
    <title>ng-show Directive</title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
  
<body> 
    <div ng-app="app" ng-controller="geek"> 
          
        <h1 style="color:green">GeeksforGeeks</h1> 
        <h2>ng-show Directive</h2> 
          
        <input id="chshow" type="checkbox" ng-model="show" /> 
          
        <label for="chshow"> 
            Show Paragraph 
        </label> 
          
        <p ng-show="show" style="background:green; color:white;  
                font-size:14px; width:35%; padding:10px;"> 
            Show this paragraph using ng-show 
        </p> 
    </div> 
      
    <script> 
        var myapp = angular.module("app", []); 
        myapp.controller("geek", function ($scope) { 
            $scope.show = false; 
        }); 
    </script> 
</body> 
  
</html>                    

輸出:
在選中複選框之前:
ngshow
選中複選框後:
ngshow

範例2:本示例使用ng-show指令顯示輸入的數字是否為5的倍數。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-show Directive</title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
  
<body ng-app="app" style="text-align:center"> 
    <div ng-controller="geek" ng-init="val=0"> 
        <h1 style="color:green">GeeksforGeeks</h1> 
        <h2>ng-show Directive</h2> 
          
        Enter a number:
        <input type="text" ng-model="val" ng-keyup="check(val)"> 
  
        <div ng-hide="show"> 
            <h3> 
                The number is multiple of 5 
            </h3> 
        </div> 
          
        <div ng-show="show"> 
            <h3> 
                The number is not a multiple of 5 
            </h3> 
        </div> 
    </div> 
      
    <script> 
        var app = angular.module("app", []); 
        app.controller('geek', ['$scope', function ($scope) { 
            $scope.check = function (val) { 
                $scope.show = val % 5 == 0 ? false:true; 
            }; 
        }]); 
    </script> 
</body> 
  
</html>                    

輸出:
ngshow



相關用法


注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 AngularJS | ng-show Directive。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。