Binding JSON objects in AngularJS

Feb 25, 2015
Facebook Twitter Google Digg Reddit LinkedIn Pinterest StumbleUpon Email


In this short blog post we will see how to bind list type data using AngularJS framework to your DOM/View. If you are just getting stated with the AngularJS please follow my previous two blog posts where I explain how to get stated with AngularJS.

Today, we will see how we can bind the list type data to our DOM elements. I am going to use the previously created application and just buildon top of that. So first let's start by creating some JSON object in our controller.

Adding JSON Data to Controller

For now we are just going to work with the Static data. In Future we will see how to bring the actual data from the server/api and bind them to the list. Let's declare a variable in our Controller which is a JSON Array.

Binding JSON list in AngularJS

Crate list using ng-repeat

One of the directive AngularJS providers is ng-repeat to display repeated items. And that is exactly what we are going to use here to display our users JSON array in our view. Modify your index.html with following code snippet highlighted in Red.

Binding JSON list in AngularJS

Remember, the initial ng-app and ng-controller bindings are already in place from our previous blog post. They are highlighted in Green.

What we are basically telling AngularJS is, Go find the variable named users in the current context(which is DemoController) and loop through every item in that list and create a new list item containing the name property for each one of these objects. And the end result is below.

Binding JSON list in AngularJS

If you want that as a table, just change the template as below.

    <table>
        <tr ng-repeat='user in users'>
            <td>{{user.index}}</td>
            <td>{{user.name}}</td>
        </tr>
    </table>

Binding JSON list in AngularJS

Auto Generating Row Number in AngularJS

Ok, so in above JSON object we had the index property representing the row number but what if we did not have such property and we still wanted to display row number next to every row in our table.

Following is the syntax to do that.

    <table>
        <tr ng-repeat='user in users'>
            <td>{{$index+2}}</td>
            <td>{{user.name}}</td>
        </tr>
    </table>

You see the special variable named $index, that will act as our row number while generating the table rows. Go ahead and run, following is the output. I have explicitly set the index from 2 for demo purposes but you can change it back to $index+1 to start from number 1.

Binding JSON list in AngularJS

Okey, that's it for today. Now that we have basic understanding of binding the list type data and single value object, we will look at event handing next.