gpt4 book ai didi

javascript - AngularJS - 如何使用另一个数组对 ng-repeat 进行排序

转载 作者:行者123 更新时间:2023-11-30 07:15:17 24 4
gpt4 key购买 nike

假设我有一组按特定顺序排列的键

orderedNames=["mike","bob","sarah];

我有一个 JSON,我想使用 ng-repeat 显示它,但按照它们在数组中出现的顺序:

{"people":
{
"bob":{
"hair":"brown",
"eyes":"blue",
"height":"tall"
},
"sarah":{
"hair":"blonde",
"eyes":"blue",
"height":"short"
},
"mike":{
"hair":"red",
"eyes":"blue",
"height":"tall"
}
}
}

我如何编写一个文件管理器,使 ng-repeat 按照数组中指定的顺序吐出人员?

<li ng-repeat="person in people | orderNames"></li>

最佳答案

您可以定义自定义过滤器。

笨蛋:http://plnkr.co/edit/fiuuGoGZK7tM5oefKQlS

index.html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
<meta charset="utf-8" />
<title>Filter Example</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.15/angular.js" data-semver="1.2.15"></script>
<script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
<li ng-repeat="person in people|orderNames:orderedNames track by $index">{{person.hair}}</li>
</body>

</html>

应用程序.js:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.people={
bob:{
hair:"brown",
eyes:"blue",
height:"tall"
},
sarah:{
hair:"blonde",
eyes:"blue",
height:"short"
},
mike:{
hair:"red",
eyes:"blue",
height:"tall"
}
};
$scope.orderedNames=["mike","bob","sarah"];

});

app.filter("orderNames",function(){
return function(input,sortBy) {
var ordered = [];
for (var key in sortBy) {
ordered.push(input[sortBy[key]]);
}

return ordered;
};
});

关于javascript - AngularJS - 如何使用另一个数组对 ng-repeat 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22697614/

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