在我的指令中,我通过范围收到一个未排序的值数组,我希望使用 ng-repeat 对其进行排序。原因是没有特殊的排序标准,我只是想确保一些标签按照我想要的顺序显示,所以在链接函数中通过indexOf和splice手动排序看起来不太好。
我想知道是否可以按照我希望显示的标签的顺序创建一个新数组,以便在 ng-repeat 中以某种方式应用。
举个例子可能有助于理解我的观点。
我的指令
$scope.unsortedLabels // ['foo1', 'foo2', 'foo3'] Array of labels I receive from parent directive
$scope.desiredLabelsOrder = ['foo3', 'foo1', 'foo2'] // The order I want the labels displayed
我的模板
<li ng-repeat="label in unsortedLabels | orderBy: ?? ></li>"
如何使用desiredLabelsOrder数组先显示foo3标签,然后显示foo1和foo2?
谢谢
最佳答案
这种情况很奇怪,但你肯定可以通过制作自定义过滤器来设计它的 Angular 。
angular.module('myApp',[]).filter('myFilter', function(){
return function(items, newArrangement){
console.log(newArrangement)
var arrayToReturn = [];
newArrangement.forEach(function(item,index){
arrayToReturn[newArrangement[item-1]] = items[index];
})
console.log(arrayToReturn)
return arrayToReturn;
};
});
并在您的ng-repeat
中使用它,您只需定义新的排列,例如
<li ng-repeat="label in unsortedLabels | myFilter: [3,1,2] ></li>
输出
foo3
foo1
foo2
希望有帮助。
关于javascript - ng-repeat orderBy - 将项目显示为数组中出现的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153345/