角度ng重复输入验证

时间:2017-12-13 16:27:36

标签: javascript angularjs validation angularjs-ng-repeat

在localstorage中保存数据之前我必须验证用户是否填写了所有输入。所有输入验证的例子都可以正常工作。直到我不熟悉Angularjs的那一刻。 任何帮助高度赞赏



var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.d1 = [];
  $scope.d2 = [];
  $scope.data = [];

  $scope.append = function() {
    $scope.data.push([]);
  };

  $scope.save = function() {
    for (var i = 0; i < $scope.d1.length; i++) {
      if ($scope.d1[i].length === 0) {
        alert("fill empty fields please");
      } else {
        localStorage.setItem('Surname', JSON.stringify($scope.d1));
      }
    }
    for (var j = 0; j < $scope.d2.length; j++) {
      if ($scope.d2[j].length === 0) {
        alert("fill empty fields please");
      } else {
        localStorage.setItem('Name', JSON.stringify($scope.d2));
      }
    }
  };
});
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
  <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-app="myApp" ng-controller="myCtrl">
  <div class="container">
    <div class="btn-group">
      <button ng-click="append()" type="button" class="btn btn-default">append</button>
      <button ng-click="save()" type="button" class="btn btn-default">Save</button>
    </div>
    <table class="table table-bordered">
      <tr>
        <th>Surname</th>
        <th>Name</th>
      </tr>
      <tr ng-repeat="x in data">
        <td><input ng-model="d1[$index]" type="text" class="form-control"></td>
        <td><input ng-model="d2[$index]" type="text" class="form-control"></td>
      </tr>
    </table>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

在输入中添加元素名称并使用&#39; required&#39;制作野外任务

   <form name="myForm" novalidate>      
..........................
<td><input ng-model="d1[$index]" type="text"
     required name="text{{$index}}" class="form-control"></td>
            <td><input ng-model="d2[$index]"
     type="text" required name="text{{$index}}"class="form-control"></td>

........</form>

在执行保存操作之前,请检查天气形式是否有效

$scope.save = function() {
   if($scope.myForm.$valid){
//add code
}else{
//display error message 
}
}

我们也可以显示字段级别验证,请参阅here