AngularJS data binding

AngularJS data binding Tutorial

Posted on November 18, 2013

One of my favourite features of Angular JS is it’s data binding. It allows you to update the view in real time as the model is updated and means you avoid manipulating the DOM

Right, lets get started. The first thing to do is setup our base page. We’ve added the ng-app attribute to the <html> tag which means that anything within the <html> tags belongs to this app. The ng-app attribute can be added anywhere and could easily be added to a div within the body tags if you wanted. I’ve added it to the <html> tag as I want to manipulate the <body> tag later on.


<html ng-app="">
<head>
    <title>
    <link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>

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

Now we need to add an input to the body tag, give it a model and then add the display the model text.

Add the folling within your body tags:

<input type="text" ng-model="data.name" />
<p>
    {{data.name}}
</p>

You’ll see that {{data.name}} now updates in real time as you update the input.

The cool thing is that data-binding isn’t just restricted to updating text and you can easily use it for more complicated scenarios like updating page styles. Lets use it to update the body background colour depending on select box options.

First add a select box within your <body> tags and assign it a model:

<select ng-model="data.color">
    <option>black</option>
    <option>Grey</option>
    <option>Green</option>
</select>

You can then use these values as a class on your body tag by updating your body tag with the following:

<body class="{{data.color}}">

We’ll add some styles to the page so that we can see the changes.

<style>
    body{
        font-family:helvetica, arial, sans-serif;
        font-size:100%;
    }
    .black{
        background:#000;
        color:#fff;
    }
    .grey{
        background:#e3e3e3;
    }
    .green{
        background:#f0ffcf;
    }
</style>

Now, when you change the select box you’ll see the body update with the relevant class.

There you have the basics of AngularJS data binding. Here’s the full code:

<!doctype html>
<html ng-app="">
<head>
    <title></title>
    <style>
        body{
            font-family:helvetica, arial, sans-serif;
            font-size:100%;
        }
        .black{
            background:#000;
            color:#fff;
        }
        .grey{
            background:#e3e3e3;
        }
        .green{
            background:#f0ffcf;
        }
    </style>
</head>
<body class="{{data.color}}">

<input type="text" ng-model="data.name">
<p>
    {{data.name}}
</p>

<select ng-model="data.color">
    <option>black</option>
    <option>grey</option>
    <option>green</option>
</select>
<p>
    {{data.color}}
</p>

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

</body>
</html>