AngularJS Data Binding

Data binding in AngularJS is the synchronization between model and view.

Data Model

An AngularJS application usually has a data model. The data model is a collection of data that can be used by the application.

Example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstname = "Bill";
  $scope.lastname = "Gates";
});

HTML View

The HTML container for the AngularJS application is called the view.

The view can access the model, and there are several ways to display model data in the view.

You can use ng-bind directive, which binds the innerHTML of the element to the specified model property:

Example

<p ng-bind="firstname"></p>

Try It Yourself

You can also use double curly braces {{ }} to display the content in the model:

Example

<p>First name: {{firstname}}</p>

Try It Yourself

Alternatively, you can use ng-model The directive binds the model to the view.

ng-model directive

Using ng-model The directive binds the data in the model to the view of HTML controls (input, select, textarea).

Example

<input ng-model="firstname">

Try It Yourself

ng-model Directives provide two-way binding between model and view.

Two-way binding

Data binding in AngularJS is the synchronization between model and view.

When the data in the model changes, the view will reflect this change, and when the data in the view changes, the model will also be updated. This happens immediately and automatically, ensuring that the model and view are always up to date.

Example

<div ng-app="myApp" ng-controller="myCtrl">
  Name: <input ng-model="firstname">
  <h1>{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstname = "Bill";
  $scope.lastname = "Gates";
});
</script>

Try It Yourself

AngularJS Controllers

The application in AngularJS is controlled by the controller. Please read about controllers in the AngularJS Controller chapter.

Due to the immediate synchronization of model and view, the controller can be completely separated from the view and only focus on model data. Thanks to data binding in AngularJS, the view will reflect any changes made in the controller.

Example

<div ng-app="myApp" ng-controller="myCtrl">
  <h1 ng-click="changeName()">{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstname = "Bill";
  $scope.changeName = function() {
    $scope.firstname = "Nelly";
  }
});
</script>

Try It Yourself