从ngRepeat访问元素
问题描述:
如何从控制器访问ngRepeat
循环内的给定记录,最终进行表单验证?从ngRepeat访问元素
我有以下的形成可动态添加的记录/用户删除:
<table class="table table-condensed span12" id="tableParticipants">
<!-- snip -->
<tbody>
<tr ng-repeat="person in people">
<td><input type="text" pattern="[0-9]*" data-provide="typeahead" placeholder="8675309" ng-model="person.empid"></td>
<td><input type="text" data-provide="typeahead" placeholder="Firstname Lastname" ng-model="person.name"></td>
<td><input type="text" placeholder="Title" ng-model="person.title"></td>
<td style="text-align: center"><i class="icon-remove" ng-click="removeParticipant()"></i></td>
</tr>
</tbody>
</table>
在提交我需要确保该雇员的ID是有效的形式,否则我会得到一个数据库错误。所以,当我通过循环工作时:
$scope.people.forEach(function(element, index, array)
{
if ($element['empid'] == BAD)
{
// set corredponding ngRepeat row to error
}
}
如何访问特定记录的给定行?
答
您应该可以执行下列操作。将一个css类名添加到数组项和/或错误消息。其余的应该由Angular处理,它将会更新。您可以选择显示/隐藏信息,添加课程等。
<tr ng-repeat="person in people" ng-class="person.error">
<td><input type="text" pattern="[0-9]*" data-provide="typeahead" placeholder="8675309" ng-model="person.empid"></td>
<td><input type="text" data-provide="typeahead" placeholder="Firstname Lastname" ng-model="person.name"></td>
<td><input type="text" placeholder="Title" ng-model="person.title"></td>
<td style="text-align: center"><i class="icon-remove" ng-click="removeParticipant()"></i> <span>{{person.errorMessage}}</td>
</tr>
if ($element['empid'] == BAD)
{
$element['errorMessage'] = 'Invalid Id'; // could bind or show a span/depends.
$element['error'] = 'error'; // set to whatever class you want to use.
}
+0
宾果。这就是我所看到的那种迂回的方式。我知道我不应该直接访问DOM元素来维护AngularJS的精神,只是没有足够好地表达它。我现在有一排排红色。谢谢! – 2013-04-30 22:24:26
+0
从jQuery做事的方式转换起初可能会很棘手..很高兴它的工作。 – lucuma 2013-04-30 22:39:18
为什么你需要这样做?您可以用错误消息填充您的人员数组,然后只需用户界面显示它是否存在... – lucuma 2013-04-30 22:10:48