Ted Scheckler
Ted Scheckler

Reputation: 1511

AngularJS using ng-repeat array key changes with filter

I have an array of zipcodes:

var zipcodes = [ 
{ "Zipcode":"00501", "State":"NY", "City":"Holtsville" }, 
{ "Zipcode":"90210", "State":"CA", "City":"Beverly Hills" },
{ "Zipcode":"00544", "State":"NY", "City":"Holtsville" }
];

I am listing them in a table as:

<input type="text" ng-model="query" placeholder="Search..."><br>
<table>
<tr ng-repeat="(key, zipcode_data) in zipcodes | filter: query" ng-click="edit_zip(key)"> 
<td>{{ zipcode_data.Zipcode }}</td>
<td>{{ zipcode_data.City }}</td>
</tr>
</table>

Clicking the row opens an edit dialog and this works fine... however, if I filter the data, the key changes. This brings up the wrong record (key) from the original array in the edit dialog (if the filtered list happens to reorder.)

For example, if I filter on city 'Holtsville', there will be two rows shown, click on the second record sends key 1, however the zipcodes array key 1 is for 90210.

$scope.edit_zip = function(index) {
 $scope.index = index;
 var modal = ngDialog.open({
  scope: $scope,
  template: 'zip_edit.html'
 });
}

Is there a way to preserve the original array index in the ng-repeat so that it properly binds to the correct array element?

Upvotes: 1

Views: 133

Answers (1)

kukkuz
kukkuz

Reputation: 42372

Always use zipcode_data and never index as later on when you add orderBy or filter you will run into issues as index is not preserved:

<input type="text" ng-model="query" placeholder="Search..."><br>
<table>
<tr ng-repeat="zipcode_data in zipcodes | filter: query" ng-click="edit_zip(zipcode_data)"> 
<td>{{ zipcode_data.Zipcode }}</td>
<td>{{ zipcode_data.City }}</td>
</tr>
</table>

and your js like this:

$scope.edit_zip = function(item) {
 $scope.item = item;
 var modal = ngDialog.open({
  scope: $scope,
  template: 'zip_edit.html'
 });
}

NOTE: You shouldn't try for a way to preserve the original array index in the ng-repeat- if you think about it, you won't be able to make it work with filter.

Upvotes: 1

Related Questions