How to sort object data source in ng-repeat in AngularJS?

Suppose I have the following users:

$scope.users = { "2": { email: 'john@gmail.com', name: 'John' }, "3": { email: 'elisa@gmail.com', name: 'Elisa' } } 

I would like to create a <select> with the following parameters:

 <option value="3">Elisa</option> <option value="2">John</option> 

In other words, users must be sorted by name.

I tried using the syntax (key, value) in expression , but it does not work:

 <option ng-repeat="(user_id, user) in users | orderBy:'user.name'" value="{{ user.id }}"> {{ user.name }} </option> 

A live example is shown here.

What am I missing?

Please do not offer solutions with ng-options , as I am using ui-select2 , which is incompatible with ng-options .

+47
angularjs angularjs-ng-repeat angularjs-orderby
Feb 19 '13 at 10:25
source share
3 answers

As long as you see this in the stream, the author answers the links in the link, I thought it would be nice to put one of the mentioned workarounds on SO:

It is true that this is not technically implemented, but there is some easy work if you want to slightly modify your data model: use a custom filter to create an array of object properties ( without ). If you add a key field to the objects ("id" in the above case), you can get the behavior you are looking for:

 app.filter("toArray", function(){ return function(obj) { var result = []; angular.forEach(obj, function(val, key) { result.push(val); }); return result; }; }); ... $scope.users = { 1: {name: "John", email: "john@gmail.com", id: 1}, 2: {name: "Elisa", email: "elisa@gmail.com", id: 2} }; 

Here you can specify the ng-repeat directive:

 <option value="{{user.id}}" ng-repeat="user in users | toArray | orderBy:'name'">{{user.name}}</option> 

And here is plunkr .

Note that the orderBy filter takes name as its parameter, not user.name .

Unfortunately, adding the id property to your objects creates the potential for inconsistency with it in the containing object.

The link mentioned in your answer also suggests suggested solutions that create the id property on user objects on the fly, but I feel that this approach is a little less messy (by introducing replication data).

+52
Sep 22 '13 at
source share

OK, I found the answer:

It has not yet been implemented :(

+9
Feb 19 '13 at 10:33
source share

By adding to the accepted answer and seeing your data format, you must convert your data as

 app.filter('myFilterUsers',function(){ return function(data) { var newRes = []; angular.forEach(data,function(val,key){ val["id"] = key; //Add the ID in the JSON object as you need this as well. newRes.push(val); }); return newRes; } }); 
0
Jan 21 '16 at 13:38 on
source share



All Articles