Two way data binding means if changes in one then it reflects in other one too immediately and in Angularjs two way data binding between model and the view is happening by ng-model
directive.
Its the synchronization between the model and the view.
When any changes in model then view reflects those changes and accordingly if any changes made in view then model gets updated as well and the main thing is it that this process does not take time.
Here you will find a simple example which make you understand the concept of two way data binding in Angularjs Example.
- <div ng-app="sampleapp" ng-controller="mycontroller">
- Product Name: <input ng-model="productname">
- <h3>{{productname}}</h3>
- </div>
- <script>
- var app = angular.module('sampleapp', []);
- app.controller('mycontroller', function($scope) {
- $scope.productname = "ExpertPHP";
- });
- </script>
Double braces {{ }}
are used to display content from model. Whatever you will type in input field then model data will change automatically.
Two way data binding in angularjs is a best way to show response of user's action immediately.
ng-app
is a root element of angularjs and every angularjs application must have ng-app
directive.
Two way data binding are prefix with =
or =attr
First i will tell you to create custom directive.
.directive
function is used to create new directive. Always use camel case name myDirective
when naming a directive and when creating html element for directive use -
separated name such as my-directive
. It is best practice to use directive via tag name.
- <my-directive></my-directive>
Directive with attribute :
- <my-directive product="myProduct"></my-directive>
Now i am going to use = local scope property for two way data binding.
Controller :
- $scope.myProduct = {name:'ExpertPHP'};
Controller defines a $scope.myProduct
object.
- angular.module('myModule').directive('myDirective', function () {
- return {
- scope: {
- product: '=' //Two-way data binding
- },
- template: '<ul><li ng-repeat="p in product">{{ p }}</li></ul>'
- };
- });
In directive i use ng-repeat
to iterate over product list and =
character inform to directive that object which are passing into the product property should be bound using two way binding and if any changes are made in outside property then product property should be automatically changed and if any changes are made into directive's product property then object in outside scope should be automatically updated as well.