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


AngularJS ng-form用法及代碼示例


AngularJS中的ng-form指令用於創建嵌套表單,即一種在另一種表單內的表單。它從HTML表單指定一個繼承控件。它在表單指令內創建控件組,該控件可用於確定控件的sub-group的有效性。

用法:

<ng-form [name="string"]> Contents... </ng-form>

範例1:本示例使用ng-form指令隱藏輸入文本字段並顯示其內容。


<!DOCTYPE html> 
<html> 
  
<head> 
    <title>ng-form Directive</title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> 
    </script>  
</head> 
  
<body ng-app="" style="text-align:center"> 
      
    <h1 style="color:green;">GeeksforGeeks</h1> 
    <h2 style="">ng-form Directive</h2> 
  
    <div> 
        <ng-form ng-hide="isDetail"> 
            Full Name:
            <input type="text" ng-model="fName"> 
            <br><br> 
            Username:
            <input type="text" ng-model="uName"> 
            <br> 
        </ng-form> 
        <br> 
        <input type="button" ng-click="isDetail=true"
                value="Click it!" /> 
                  
        <div ng-show="isDetail"> 
            First Name:<b>{{fName}}</b><br /> 
            User Name:<b>{{uName}}</b><br /> 
        </div> 
    </div> 
</body> 
  
</html>                    

輸出:
單擊按鈕之前:
ngform
單擊按鈕後:
ngform

範例2:本示例使用ng-form指令來驗證電子郵件並保存。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>ng-form Directive</title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> 
    </script>  
</head> 
  
<body ng-app="" style="text-align:center"> 
      
    <h1 style="color:green;">GeeksforGeeks</h1> 
    <h2 style="">ng-form Directive</h2> 
  
    <div> 
        <ng-form ng-submit="save(user)" name="myForm" novalidate> 
          
            Enter Email:
            <input type="email" name="uname"
                required ng-model="user.userName"><br> 
                  
            <span style="color:red" ng-show="myForm.uname.$error.required 
                    && myForm.uname.$dirty">Email is required</span> 
            <br> 
              
            <button ng-disabled="!myForm.$valid" type="submit"> 
                save 
            </button> 
        </ng-form> 
    </div> 
</body> 
  
</html>                    

輸出:
輸入無效:
ngform
有效輸入:
ngform



相關用法


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