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


AngularJS ng-click用法及代碼示例


AngluarJS中的ng-click指令用於單擊元素時應用自定義行為。它可以用於顯示/隱藏某些元素,或者在單擊按鈕時可以彈出警報。

用法:

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

範例1:本示例使用ng-click指令在單擊元素後顯示警報消息。


<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-click Directive</title> 
  
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
   
<body ng-app="geek" style="text-align:center"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
    <h2>ng-click Directive</h2> 
      
    <div ng-controller="app"> 
        <button> 
            <a href="" ng-click="alert()"> 
                Click Here 
            </a> 
        </button> 
    </div> 
      
    <script> 
        var app = angular.module("geek", []); 
        app.controller('app', ['$scope', function ($app) { 
            $app.alert = function () { 
                alert("This is an example of ng-click"); 
            } 
        }]); 
    </script> 
</body> 
  
</html>

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

範例2:本示例使用ng-click指令在單擊元素後顯示一些內容。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-click Directive</title> 
  
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
   
<body ng-app="" style="text-align:center"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
    <h2>ng-click Directive</h2> 
      
    <form name="form"> 
        <div ng-hide="isShow"> 
            Enter Name:  <input type="text" required ng-model="Name" /> 
              
            <br><br> 
              
            <input type="button" ng-disabled="form.$invalid"
                    ng-click="isShow = true" value="Sign in" /> 
        </div> 
          
        <div ng-show="isShow"> 
            Sign in successful.<br> 
            <input type="button" ng-click="isShow = false;Name=''"
                    value="Logout" /> 
        </div> 
    </form> 
</body> 
  
</html>

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



相關用法


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