Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS orderBy does not work with track by in ngOptions?

Tags:

angularjs

I am trying to sort ngOptions with track by

This is my template

<select ng-model="asd" ng-options="user.id as user.name for user in users track by user.id | orderBy: 'name'"> 

This is my controller

function AppCtrl($scope) {   $scope.users = [    {id : 25, name: 'Batista'},    {id : 26, name: 'Ultimate Warrior'},    {id : 27, name: 'Andre the giant'}   ];   $scope.name = 'asdasd';   $scope.asd = 25;  } 

I wrote a snippet in JSBin to demonstrate this. The problem with this is the sorting does not work. Should I write a custom filter?

like image 374
tastebuds Avatar asked May 29 '14 03:05

tastebuds


1 Answers

In order to use tracking with filters, the track by expression needs to be added after the filter.

Try this instead:

user.id as user.name for user in users | orderBy: 'name' track by user.id 

The documentation for ngRepeat mentions this under the "Arguments" section, specifically:

Filters should be applied to the expression, before specifying a tracking expression.

and

For example: item in items | filter:searchText track by item.id is a pattern that might be used to apply a filter to items in conjunction with a tracking expression.

like image 79
Ahmad Mageed Avatar answered Sep 22 '22 22:09

Ahmad Mageed