【问题标题】:AngularJS using ng-repeat array key changes with filterAngularJS 使用带有过滤器的 ng-repeat 数组键更改
【发布时间】:2016-12-04 09:47:36
【问题描述】:

我有一个邮政编码数组:

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 中保留原始数组索引,以便正确绑定到正确的数组元素?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢...我没想过只传递 zipcode_data,这正是我需要的。
    猜你喜欢
    • 2016-07-31
    • 2014-08-17
    • 2016-09-19
    • 1970-01-01
    • 2020-05-28
    • 2018-01-28
    • 2019-06-16
    • 1970-01-01
    • 2019-10-25
    相关资源
    最近更新 更多