ng-repeat orderBy对象

时间:2014-12-13 01:41:17

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

更新:

在我的html页面上,我使用如下:

<section ng-repeat="template in templates">
        <ng-include src="template"></ng-include>
    </section>

但问题是我需要特定顺序的特定文件,所以有没有办法控制顺序呈现的方式?

我试图按一个对象排序我该如何做,我在网上搜索后才发布。

function MyCtrl($scope) {
    $scope.templates = {
        template_address: "../template/address.html",
        template_book: "../template/book.html",
        template_create: "../template/create.html" 
    };



<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="(name, path) in templates">{{name}}: {{path}}</li>
    </ul>
</div>

http://jsfiddle.net/abuhamzah/6fbpdm9m/

4 个答案:

答案 0 :(得分:15)

您无法将过滤器应用于普通对象only to arrays

您可以做的是在控制器中定义一个方法,将对象转换为数组:

$scope.templatesAry = function () {
    var ary = [];
    angular.forEach($scope.templates, function (val, key) {
        ary.push({key: key, val: val});
    });
    return ary;
};

然后过滤:

<li ng-repeat="prop in templatesAry() | orderBy:'-key'">
     {{prop.key}}: {{prop.val}}
</li>

Example

答案 1 :(得分:1)

所以我认为这会起作用,它也会保持相同的对象指针

app.filter('orderObjectBy', [function()  {
  return (filterObj, prop) => {

let arr = []
//below is the loadash function you can use for in also
_.forEach(filterObj, function(value, key)  {
  arr.push({
    key: key,
    value: value
  });
});

let sortedArr = _.sortBy(arr, val => val.value[prop]);

for (let variableKey in filterObj) {
  if (filterObj.hasOwnProperty(variableKey)) {
    delete filterObj[variableKey];
  }
}

for (let data of sortedArr) {
  filterObj[data.key] = data.value;
}


    return filterObj;

  }
}])

答案 2 :(得分:0)

您可以将其用作item.key之后,无需将其保留为对象,将Key包含在数据字段中,并使其成为数组;您可以使用_.omit

将其删除

filter = function(items){

filtered = {};

_。mapObject(items,function(V,K){

V.key = K; // Include the key in the data; your can _.omit it after 

if(V.name ='test'){filtered [K] = V;};

});

返回_.sortBy(已过滤,'anyFieldSortCoudBeThe KEY it self'); // sortBy将返回已排序的数组 };

答案 3 :(得分:-4)

归功于ryeballar

https://stackoverflow.com/a/27466368/275390

为什么不使用数组,而不是使用键值对象? ng-repeat通过迭代对象/数组的索引对迭代进行排序。

FORKED DEMO

  $scope.templates = [
    'create.html',
    'book.html',
    'address.html'
  ];