我有一个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中保留原始数组索引,以便正确绑定到正确的数组元素?
答案 0 :(得分:1)
始终使用zipcode_data
而不是index
稍后当您添加orderBy
或filter
时,您将遇到问题,因为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
一起使用。