31

My array is : BS. Its structure is :

Array[317]
0: Object
   $$hashKey: "022"
   name: "Los Angeles Comm."
.
.
.
..

BS is an array. Each value is a JSon object with filed of name.

I want to sort all the values of BS according to their name. I am trying :

<option ng-repeat="item in BS | orderBy:item.name"  value="{{item.name}}">{{item.name}}</option>

I have also tried : orderBy:name and orderBy:item[name]. Nothing works. Why is this not working and whats the correct code?

Bhumi Singhal
  • 8,063
  • 10
  • 50
  • 76

1 Answers1

80

Have a look at below html

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
</head>
<body>
    <div ng-controller="item">
        <ul>
            <li ng-repeat="item in items|orderBy:'name'">
                {{item.name}}
            </li>
        </ul>
    </div>
    <script>
        var AppModule = angular.module('app', []);
        function item($scope) {
            $scope.items = [{ name: 'tur' }, { name: 'abc' }, { name: 'xyx' }];

        }
    </script>
</body>
</html>
Ajay Beniwal
  • 18,857
  • 9
  • 81
  • 99
  • 13
    One thing to note here is that if you use the `track by ---` syntax, your orderBy will no longer work. – dmackerman Sep 27 '13 at 03:56
  • 45
    @dmackerman, `track by ---` must always be at the very end of the entire expression, including to the right of filters. Then `orderBy` works as expected. – nilskp Mar 11 '14 at 18:45
  • @nilskp, is there any documentation that tells why `track by` must be at the end? I'm wondering why `track by` is allowed anywhere else other than at the end if it causes undesired behavior. – adam0101 May 15 '14 at 21:58
  • Darn didnt know you needed to wrap in apostrophe's! Thank you. – Kiee Jun 16 '15 at 08:28