在angular中,如何对使用过滤器显示的字段使用orderBy和ngRepeat,从而改变它们的实际内容

In angular, how to use orderBy with ngRepeat on fields that are displayed using filters, changing their actual content?

本文关键字:改变 ngRepeat 字段 angular 过滤器 orderBy 显示      更新时间:2023-09-26

我正在使用ngRepeat迭代对象数组。对象有一个字段"teamId"。在迭代中,我使用类似于{{object.teamId | teamName}}的过滤器来显示字段,其中teamName过滤器接受一个teamId并返回一个实际的团队名称。

我如何在ngRepeat中使用orderBy过滤器来按团队名称而不是团队id订购数组,如果团队名称不是对象中的字段,而是过滤器的结果?

你没有。您需要预处理您的数据,以便您的对象包含一个团队名称属性,以便您可以基于它进行排序。过滤器只更改数据的显示,它不修改数据,因此orderBy不知道您更改的数据。

<div ng-repeat="option in options" >
   {{ option | teamname }} <!-- filter changes the displayed value, not the data -->
</div>

//JS

angular.forEach($scope.options, function(index, value){ // or (value, index), I forget
    $scope.options[index] = $filter('teamname',$scope.options, index+1); // (filtername, array, expression) //this is a hack and you can probably get a more efficient way to pass these params
});

//JS

$scope.options = $filter('teamname',$scope.options);