AngularJS Data Binding
AngularJS Data Binding tutorial will drive you on various ways of data binding from controller to view. As you all know, angularjs follows two way data binding:
- When model changes at controller corresponding data on view changes
- when data changes at view level then it data in model also reflected at controller level
Data binding ways:
-
Using Angular Expression {{}}
-
<div ng-controller="DataBndCtrl" > <label>{{labelName}}:</label>{{value}} </div> <script> var app = angular.module('DataBindingDemo', []); app.controller("DataBndCtrl",['$scope',function($scope){ $scope.labelName = "Email Address"; $scope.value="[email protected]"; }]); </script>
-
One-time binding Using Expression
AngularJS provides you one time binding expression to display the model values on first time only and it doesn’t displays even model changes. One-time expression starts with
::
is and it de-registers the binding.-
<div ng-controller="DataBndCtrl" > <label>{{labelName}}:</label>{{::value}} <input type="text" ng-model="value"/> </div> <script> var app = angular.module('DataBindingDemo', []); app.controller("DataBndCtrl",['$scope',function($scope){ $scope.labelName = "Email Address"; $scope.value="[email protected]"; }]); </script>
-
- {{::value}} is one time expression and {{value}} is binded with <input> control. It displays “[email protected]” always, even if you enter value in the input box then it won’t change the display value. It means, it binds to model for one time only.
-
-
ng-bind
- ng-bind can also be used to display the model value. It replaces the html attribute with bind expression text
- ng-bind-html tag is used to display html content
- ng-bind-template is used to display multiple model attributs
-
<body ng-app="DataBindingDemo" ng-controller="MainController"> <div ng-controller="DataBndCtrl" > <label ng-bind="labelName"></label>:<span ng-bind="value"></span> <p ng-bind-template="{{labelName}} {{value}}" /> <br/><input type="text" ng-model="value"/> </div>
-
ng-model
- ng-model binds form control elements: input,textarea,select and adds css classes for each control element: ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched, ng-empty, ng-not-empty
- ng-model also provides validtions
-
<input type="text" ng-model="value"/>