ng-repeat orderBy object

此生再无相见时 提交于 2019-11-29 10:25:23
JLRishe

You can't apply a filter to a plain object, only to arrays.

What you can do is define a method in the controller to convert the object to an array:

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

and then filter that:

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

Example

so i think this would work and it also maintains the same object pointer,

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;

  }
}])

YOU not need to Keep it as Object , include the Key inside data filed , and make it array , after you can Use it as item.key ; and you can remove it with _.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;};

});

return _.sortBy(filtered,'anyFieldSortCoudBeThe KEY it self'); //sortBy will return array sorted };

Nick Kahn

Credit goes to ryeballar

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

Instead of using a key-value object, why not use an array? ng-repeat orders the iteration by the index of the iterated object/array.

FORKED DEMO

  $scope.templates = [
    'create.html',
    'book.html',
    'address.html'
  ];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!