Ng-repeat orderBy object

UPDATE:

on my html page, which I use as follows:

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

but the problem is that I need a specific file in a specific order, so is there a way I can control how the order is rendered?

I am trying to arrange the object, how can I do it, and I searched for it 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/

+5
source share
3 answers

You cannot apply a filter to a simple 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 this:

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

Example

+12

, , ,

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;

  }
}])
+1

The loan goes to ryeballar

fooobar.com/questions/1567305 / ...

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

FORKED DEMO

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

All Articles