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


AngularJS ng-disabled用法及代碼示例

AngularJS中的ng-disabled指令用於啟用或禁用HTML元素。如果ng-disabled屬性內的表達式返回true,則表單字段將被禁用,反之亦然。它通常應用於表單字段(輸入,選擇,按鈕等)。

用法:

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

範例1:本示例使用ng-disabled指令禁用按鈕。


<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-disabled 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"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
      
    <h2>ng-disabled Directive</h2> 
      
    <div ng-controller="app" ng-init="disable=false"> 
        <button ng-click="geek(disable)" ng-disabled="disable"> 
            Click to Disable 
        </button> 
          
        <button ng-click="geek(disable)" ng-show="disable"> 
            Click to Enable 
        </button> 
    </div> 
      
    <script> 
        var app = angular.module("app", []); 
        app.controller('app', ['$scope', function ($app) { 
            $app.geek = function (disable) { 
                $app.disable = !disable; 
            } 
        }]); 
    </script> 
</body> 
  
</html>

輸出:
在單擊按鈕之前:
ngdisabled
單擊按鈕後:
ngdisabled

範例2:本示例使用ng-disabled指令使用複選框啟用和禁用按鈕。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-disabled 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"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
      
    <h2>ng-disabled Directive</h2> 
      
    <div ng-controller="geek"> 
        <h4> 
            Check it  
            <input type="checkbox" ng-model="check" /> 
        </h4> 
          
        <button type="button" ng-disabled="!(check)"> 
            Click to submit 
        </button> 
    </div> 
      
    <script> 
        var app = angular.module("app", []); 
        app.controller('geek', ['$scope', function ($scope) { 
            $scope.disableClick = function (isDisabled) { 
            $scope.isDisabled = !isDisabled; 
            } 
        }]); 
    </script> 
</body> 
  
</html>

輸出:
在單擊按鈕之前:
ngdisabled
單擊按鈕後:
ngdisabled



相關用法


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