0

私はAngularが初めてで、重要な入力検証を行いたいと思っています。

基本的に私はテーブルを持っています。各行には 3 つのテキスト入力が含まれます。ユーザーがテキスト入力を入力するとき、テーブルに 3 つの空白以外の入力フィールドを持つ行が少なくとも 1 つ含まれているかどうかを確認したいと思います。もしそうなら、私はメッセージを表示したい。

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?
}

これは問題を示すプランカーです: http://plnkr.co/edit/Ws3DxRPFuuJskt8EUqBB

4

1 に答える 1

3

正直なところ、これをフォームの検証とは呼びません。しかし、初心者にとっては、テンプレート内の配列ではなく、オブザーバーに実際のモデルがあれば、はるかに簡単になります。あなたが始めた方法は、コントローラー内で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/

于 2013-11-13T14:43:19.163 に答える