AngularJS Data Binding is the automatic synchronization of data between the model and the view, enabling dynamic updates in the user interface when the underlying data changes.
var app = angular.module(‘myApp’, []); app.controller(‘myCtrl’, function($scope) { $scope.firstname = “John”; $scope.lastname = “Doe”; }); |
The HTML container that displays the AngularJS application is referred to as the view.
The view has access to the model, and there are various methods for presenting model data within it. One option is to use the ng-bind directive, which binds the innerHTML of the element to the specified model property.
<p ng-bind=”firstname”></p> |
You can also use double braces {{ }} to display content from the model.
<p>First name: {{firstname}}</p> |
Alternatively, you can use the ng-model directive on HTML controls to connect the model to the view.
Utilize the ng-model directive to bind data from the model to the view for HTML controls such as input, select, and textarea.
<input ng-model=”firstname”> |
The ng-model directive enables two-way binding between the model and the view.
Data binding in AngularJS refers to the synchronization between the model and the view. When the data in the model changes, the view updates accordingly, and conversely, when the data in the view changes, the model is also updated. This process occurs instantly and automatically, ensuring that both the model and the view remain in sync at all times.
<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 = “John”; $scope.lastname = “Doe”; }); </script>
|
Applications in AngularJS are managed by controllers. You can learn more about controllers in the AngularJS Controllers chapter. Due to the immediate synchronization between the model and the view, the controller can be entirely independent of the view and focus solely on the model data. Thanks to data binding in AngularJS, any changes made in the controller will be reflected in the view.
<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 = “John”; $scope.changeName = function() { $scope.firstname = “Nelly”; } }); </script>
|