gpt4 book ai didi

javascript - Angular 新手: non-trivial form validation?

转载 作者:行者123 更新时间:2023-11-28 20:10:43 25 4
gpt4 key购买 nike

我是 Angular 新手,我想做一些重要的输入验证。

基本上我有一张 table 。每行包含三个文本输入。当用户输入任何文本输入时,我想检查该表是否至少包含一行具有三个非空​​白输入字段。如果是的话,我想显示一条消息。

我不知道如何在 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>

和 Controller :

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

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

最佳答案

说实话,我不会将此称为“表单验证”。但对于初学者来说,如果您有一个真实模型来观察,而不是模板中的数组,那么事情会简单得多。您开始的方式将(或者至少可能)导致您在 Controller 内进行 dom 操作,这对于 Angular 来说是不行的。

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

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/

关于javascript - Angular 新手: non-trivial form validation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19955759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com