30

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?

1 Answer 1

79

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>
Sign up to request clarification or add additional context in comments.

4 Comments

One thing to note here is that if you use the track by --- syntax, your orderBy will no longer work.
@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, 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.
Darn didnt know you needed to wrap in apostrophe's! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.