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

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

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

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/

相关文章:

javascript - 滚动处理程序错误

c++ - 我如何使用 C++ STL Sort 对具有继承的对象数组进行排序

objective-c - 将具有属性的对象数组保存到 plist

javascript - 打开多个 mdDialog 框

javascript - 如何将选项标签的相同数据标识归因于其他元素?

javascript - 新日期 ('dd/mm/yyyy' )而不是 newDate ('mm/dd/yyyy' )

javascript - 点击后退按钮后未执行 JS 代码

javascript - 如何将数组中的每个元素与多个条件进行比较?

angularjs - 如何使用 $location、Angular 在浏览器中打开新选项卡?

angularjs - 如何从浏览器中抑制 "Authentication Required"弹出窗口?