AngularJS orderBy子属性不起作用

时间:2015-06-05 18:07:46

标签: angularjs angularjs-ng-repeat ng-repeat angularjs-orderby

如何通过子属性"active" : true订购商品列表?第一个节点是每个朋友的动态插入ID。

<li data-ng-repeat="friend in friends|orderBy:'friend.active':true">
        <span class="name">{{friend.name}}</span>
        <span class="phone">{{friend.lastName}}</span>
</li>

$scope.friends = {
    "12345": {
        "name": "Dhiraj",
        "lastName": "Agarwal",
        "active" : false
    },
    "23456": {
        "name": "Poonam",
        "lastName": "Mittal",
        "active" : false
    },
    "34567": {
        "name": "Suresh",
        "lastName": "Bansal",
        "active" : true
    },
    "45678": {
        "name": "Usha",
        "lastName": "Goel",
        "active" : false
    }
};

2 个答案:

答案 0 :(得分:0)

获得解决方案

http://justinklemm.com/angularjs-filter-ordering-objects-ngrepeat/

github.com/fmquaglia/ngOrderObjectBy

创建了一个新过滤器,然后用于订购

plnkr:plnkr.co/edit/4eCq7yaVyXGZB8etLZhN?p=preview

<li data-ng-repeat="friend in friends|orderObjectBy:'active':true">

app.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

答案 1 :(得分:-1)

常规ng-filter orderBy只接受数组。

使用这种数据可以正常工作:

 $scope.friends = [{
            "name": "Dhiraj",
                "lastName": "Agarwal",
                "active": false

    },  {
            "name": "Poonam",
                "lastName": "Mittal",
                "active": false

    },{
            "name": "Suresh",
                "lastName": "Bansal",
                "active": true

    }, {
            "name": "Usha",
                "lastName": "Goel",
                "active": false

    }];

jsfiddle demo

编辑: 如果您不想使用数组,则可以使用此角度issue

中描述的变通方法

过滤器(未经过调整并使用下划线):

app.filter('toArray', function() { return function(obj) {
    if (!(obj instanceof Object)) return obj;
    return _.map(obj, function(val, key) {
        return Object.defineProperty(val, '$key', {__proto__: null, value: key});
    });
}});

示例标记:

<div ng-repeat="val in object | toArray | orderBy:'priority' | filter:fieldSearch">
  {{val.$key}} : {{val}} 
</div>