使用ng-repeat数组键的AngularJS随过滤器而变化

时间:2016-07-29 15:49:11

标签: javascript angularjs arrays filter angularjs-ng-repeat

我有一个zipcodes数组:

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

我将它们列在表格中:

<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>

单击该行会打开一个编辑对话框,这样可以正常工作...但是,如果我过滤数据,则密钥会更改。这会在编辑对话框中显示原始数组中的错误记录(键)(如果已过滤的列表恰好重新排序。)

例如,如果我在城市'Holtsville'上过滤,则会显示两行,点击第二条记录发送密钥1,但是zipcodes数组键1是90210。

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

有没有办法在ng-repeat中保留原始数组索引,以便正确绑定到正确的数组元素?

1 个答案:

答案 0 :(得分:1)

始终使用zipcode_data而不是index稍后当您添加orderByfilter时,您将遇到问题,因为index未被保留:< / p>

<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>

你的js是这样的:

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

注意: 您不应该尝试在ng-repeat中保留原始数组索引的方法 - 如果您考虑它,您将无法使其与filter一起使用。