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

← PrevNext →

AngularJS filters are versatile tools that can be used in expressions and directives. In this article, I’ll show you how to add the AngularJS orderBy filter to a directive. We will render a list of predefined books using the ng-repeat directive. Although the list is initially in a random order, we'll use the orderBy filter to display the books in alphabetical order for better readability and organization.

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 built-in 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 →