gpt4 book ai didi

javascript - AngularJS 使用 ng-repeat 数组键通过过滤器进行更改

转载 作者:行者123 更新时间:2023-11-27 22:42:15 25 4
gpt4 key购买 nike

我有一个邮政编码数组:

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,但邮政编码数组键 1 对应的是 90210。

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

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

最佳答案

始终使用zipcode_data,切勿使用index,因为稍后当您添加orderByfilter时,您会遇到问题是 index 未保留:

<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 一起使用。

关于javascript - AngularJS 使用 ng-repeat 数组键通过过滤器进行更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38662833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com