当前位置: 首页 > 工具软件 > ng-dynamic > 使用案例 >

AngularJS 指令ng-form

齐夕
2023-12-01

由于AngularJS中用来取代<form>ng-form指令可以嵌套,并且外部表单在所有子表单都合

法之前一直处于不合法状态,因此我们可以在动态生成子表单的同时使用表单验证功能。是的,

鱼和熊掌可以兼得。

<!doctype html>
<html ng-app="myApp">
<head>
  <link rel="stylesheet" href="//cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
</head>
<body>
  
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
  <div ng-repeat="field in fields" ng-form="signup_form_input">
    <input type="text"
           name="dynamic_input"
           ng-required="field.isRequired"
           ng-model="field.name"
           placeholder="{{field.placeholder}}" />
    <div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid">
      <span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The field is required.</span>
    </div>
  </div>
  <button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
</form>
  
</body>
</html>

 

input.ng-invalid {
  border: 1px solid red;
}

input.ng-valid {
  border: 1px solid green;
}

 

angular.module('myApp', [])
.controller('FormController', function($scope) {
  $scope.fields = [
    {placeholder: 'Username', isRequired: true},
    {placeholder: 'Password', isRequired: true},
    {placeholder: 'Email (optional)', isRequired: false}
  ];

  $scope.submitForm = function() {
    alert("it works!");
  };
});

 

转载于:https://www.cnblogs.com/ByronWu12345/p/4853297.html

 类似资料: