ngRepeat - 首先按特定键对对象排序

时间:2017-03-31 10:04:53

标签: javascript angularjs

我正在编写一个AngularJS应用程序(Angular 1),它需要在页面上显示一个表列表。但是,某些键需要首先显示如下:

Reference group 'Implicit (Apache Cordova)' not found.

我发现我需要使用orderBy filter,但我似乎无法正常工作。有谁知道我怎么能做到这一点?

JS:

<div>baz (data)</div>
<div>bar (data)</div>
<div>foo (data)</div>
<div>baa (data)</div>

HTML:

angular.module("MyModule").controller("Test", function() {

    this.sort = ["baz", "bar"];

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

});

2 个答案:

答案 0 :(得分:1)

您需要使用orderBy,但遗憾的是,这不能与对象配合使用,因此您必须编写自定义toArray过滤器。

angular.module("MyModule").controller("Test", function() {

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

    this.customSort = function(a, b){
        /* Whatever way you need to do this */
        var sort = ["baz", "bar"];
        return sort.indexOf(a) < sort.indexOf(b) ? 1 : -1;
    }

}).filter('toArray', function () {

    return function (obj) {
        if (!(obj instanceof Object)) {
            return obj;
        }

        return Object.keys(obj).map(function (key) {
            return Object.defineProperty(obj[key], '$key', {__proto__: null, value: key});
        });
    }
});

HTML

<div ng-controller="Test as T">
  <div ng-repeat="item in T.data | toArray | orderBy: $key : false : T.customSort">
    {{ item.$key }} ({{ item.value }})
  </div>
</div>

Angular orderBy docsDiscussion on orderBy for objects

答案 1 :(得分:0)

<div ng-repeat="item in T.data | orderBy: customFilter
{{ item.$key }} ({{ item.value }}

this.customFilter(obj){
switch(key){//key is actual value of cases like `baz`,`bar`
   case "baz":return 0;
   case "bar":return 1;
   case "foo":return 2;
   case "baa":return 3;
   default:return 99;
}
}