角度新手:非平凡的形式验证

Angular newbie: non-trivial form validation?

本文关键字:验证 新手      更新时间:2023-09-26

我是Angular的新手,我想做一些不平凡的输入验证。

基本上我有一张桌子。每行包含三个文本输入。当用户键入任何文本输入时,我想检查表格是否至少包含一行和三个非空白输入字段。如果是这样,我想显示一条消息。

我不知道如何在 Angular 中干净利落地做到这一点,任何帮助将不胜感激。

这是我的 HTML:

<tr data-ng-repeat="i in [1,2,3,4,5]">
  <td data-ng-repeat="i in [1,2,3]">
    <input ng-model="choice.selected" ng-change='checkAnswer(choice)' type="text" />
  </td>
</tr>
... 
<div ng-show="haveCompleteRow">we have a complete row!</div>

和控制器:

$scope.haveCompleteRow = false;
$scope.checkAnswer=function(choice){
  $scope.haveCompleteRow = true; // what to do here?
}

这是一个演示该问题的 plunker:http://plnkr.co/edit/Ws3DxRPFuuJskt8EUqBB

老实说,我不会称这种形式为验证。但对于初学者来说,如果你有一个真实的模型来观察,而不是模板中的数组,那就简单多了。你开始的方式将,或者至少可以引导你在控制器内部进行dom-manipulation,这是角度的禁忌。

带有模型的简单第一个草图可以是:

app.controller('TestCtrl', ['$scope', function ($scope) {
  $scope.rows = [
    [{text: ''}, {text: ''}, {text: ''}],
    [{text: ''}, {text: ''}, {text: ''}],
    [{text: ''}, {text: ''}, {text: ''}]
  ];
  $scope.haveCompleteRow = false;
  // watch for changes in `rows` (deep, see last parameter `true`).
  $scope.$watch('rows', function (rows) {
    // and update `haveCompleteRow` accordingly
    $scope.haveCompleteRow = rows.some(function (col) {
      return col.every(function (cell) {
        return cell.text.length > 0;
      });
    });
  }, true);
}]);

跟:

<body ng-controller="TestCtrl">
  <table>
    <thead>
      <tr>
        <th>Col1</th>
        <th>Col2</th>
        <th>Col3</th>
      </tr>
    </thead>
    <tbody>
      <tr data-ng-repeat="row in rows">
        <td data-ng-repeat="cell in row">
          <input ng-model="cell.text" type="text" />
        </td>
      </tr>
    </tbody>
  </table>
  <div ng-show="haveCompleteRow">we have a complete row!</div>
</body>

作为模板。

演示:http://jsbin.com/URaconiX/2/