2013-04-30 95 views
0

如何從控制器訪問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 
    } 
} 

如何訪問特定記錄的給定行?

+0

爲什麼你需要這樣做?您可以用錯誤消息填充您的人員數組,然後只需用戶界面顯示它是否存在... – lucuma 2013-04-30 22:10:48

回答

2

您應該可以執行下列操作。將一個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