Roee Distler Roee Distler - 1 year ago 77
AngularJS Question

$index does not exist in ng-repeat - the answer is inside my original post

I have a problem getting $index inside a ng-repeat when trying to bind it to checkbox. First, I assign an array that looks like:

var_dump from php:

array(3) {
[0] => array(9) {
["first_name"] => string(3)
"emp" ["last_name"] => string(5)
"loyee" ["username"] => string(4)
"emp1" ["email"] => string(22)
"" ["id"] => string(3)
"539" ["rights_type"] => string(1)
"3" ["editProfile"] => bool(true)["sendMessage"] => bool(true)["editApps"] => bool(false)
}[1] => array(9) {
["first_name"] => string(3)
"one" ["last_name"] => string(4)
"more" ["username"] => string(4)
"emp2" ["email"] => string(19)
"" ["id"] => string(3)
"540" ["rights_type"] => string(1)
"0" ["editProfile"] => bool(false)["sendMessage"] => bool(false)["editApps"] => bool(false)
}["isEmpty"] => bool(false)

my code looks like this:

<tr ng-repeat="employee in employees.result track by $index" ng-if="employee.username">
<th class="col-md-1" scope="row">{{employee.username}} - ({{employee.first_name}} {{employee.last_name}})</th>
<td class="col-md-1"><input type="checkbox" ng-model="employees.result.$index.editProfile"></td>
<td class="col-md-1"><input type="checkbox" ng-model="employees.result.$index.sendMessage"></td>
<td class="col-md-1"><input type="checkbox" ng-model="employees.result.$index.editApps"></td>

This object is being attached to the $scope in the controller. Important to say that the ng-repeat does work and I get the right values of first name, username etc, it's just the $index that I can't get.
When I try to just print {{$index}} i get nothing. I tried to delete the "isEmpty" key from the array but it did not help as well. Any ideas?

all i had to change is employees.result to employee and it actually updated employees.result (every single cell of the array separately), so it looks like:

{{employee.username}} - ({{employee.first_name}} {{employee.last_name}})

Answer Source


I think the issue is that when you are referencing employees inside of a loop that is currently looking at a single employee

as I mentioned I have never used $index so I am not sure but I would also double check if you need to reference it in there (as your WORKING code does not reference it at all)

In your code try changing:

<td class="col-md-1"><input type="checkbox" ng-model="employees.result.$index.editProfile"></td>


<td class="col-md-1"><input type="checkbox" ng-model="employee.result.editProfile"></td>

In the case that it DOES need to be referenced, I would imaging the reference would look more like:

<input type="checkbox" ng-model="employee.result[$index].editProfile">

as indexes are normally referenced.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download