Set an Order for an Array of Values using AngularJS orderBy Filter

← PrevNext →

We can use AngularJS filters in expressions, as well as in directives. Here I’ll show you how to add AngularJS “orderBy” Filter to a directive. We will render a list of pre-defined books using the “ng-repeat” directive. I have added the list in a random fashion. However, I wish to render the books in alphabetic order.

This article is a part of a series of articles, which I have written before explaining various AngularJS Filters (Introduction to Filters). My previous articles also covered some commonly used filters such as the AngularJS “uppercase” filter, how you can inject the AngularJS “date” filter in a Controller, how you can format a string using the “currency” filter. In addition, you can refer the link that I have provided in the Related Articles section below.

Now let’s get back to this article.

The first example shows the list in its default order.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>

<body>
    <div ng-app 
        ng-init="list=[
        { name:'Computer Architecture' }, 
        { name:'Advanced Composite Materials' }, 
        { name:'Stategies Unplugged' }, 
        { name:'Teaching Science' }, 
        { name:'Challenging Times' }]">

        <!-- LOOP.-->
        <div ng-repeat="books in list">
            <div>{{ books.name }} </div>
        </div>
    </div>
</body>
</html>
Try it

Now, let us add the in-built orderBy filter to the ng-repeat directive.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>

<body>
    <div ng-app 
        ng-init="list=[
        { name:'Computer Architecture' }, 
        { name:'Advanced Composite Materials' }, 
        { name:'Stategies Unplugged' }, 
        { name:'Teaching Science' }, 
        { name:'Challenging Times' }]">

        <div ng-repeat="books in list | orderBy:'name'">
            <div>{{ books.name }} </div>
        </div>
    </div>
</body>
</html>
Try it

The variable name has the values. See how I have added the filter orderBy followed by the variable. Please remember, filters are case sensitive and you must write yours variables inside single quotes (' ').

← PreviousNext →