当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。