ng-repeat orderBy object

2019-01-26 13:10发布

问题:

UPDATE:

on my html page I'm using as the following:

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

but the problem is that I need specific file in certain order so is there a way I can control the way order is rendering?

I'm trying to orderby an object how do I do that and I have searched online before posting it here.

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/

回答1:

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



回答2:

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;

  }
}])


回答3:

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 };



回答4:

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'
  ];