Getting Started With AngularJS – Data Binding & Model

In this blog post we are going to see one of most important aspects of angularjs i.e data binding.

AngularJS has a two way data binding, lets see with examples what this means.

Lets change out index.html file to

<body ng-app='MainApp'>
    <div ng-controller='MainCtrl'>
        Change Text Here: 
        <input type='text' ng-model='text' />
        <p>Text: {{text}}</p>

and our app.js to

var mainMod = angular.module('MainApp', []);

mainMod.controller('MainCtrl', function ($scope) {
    $scope.text = '';

In the above example, you will see as soon as any text is entered into the text field it is dynamically updated to the {{text}} variable. This is called two way data binding, i.e the underlying data and DOM have been tightly coupled together.

Angular Expressions

Angular expressions are written inside {{}} and are just basic javascript code snippets. These snippets are evaluated on the controller $scope. More details about angular extensions can be seen here

e.g on angular expressions are

{{number + 1}}

In all the above expressions the variables number, items, product are defined in the controller $scope.

Angular Model

ng-model is a way to bind form fields to controller $scope. It can be assigned to input types, select, textarea etc and establish a two way data binding. ng-model is mainly useful for form fields, validation and form submission which we see in detail later.