Here I come with the next article about Angular JS series and it is about data binding and directives in Angular JS. I have explained basics about data binding in the first article also and Today we will go in depth so you can use data binding function of AngularJS very easily and skillfully.
ng-bind {{expression}}:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE> <html> <head> <script src = "js/angular.js" ></script> </head> <body ng-app> <input ng-model="name" /> <p>Hello {{name}}, </p> 11 <p>Display ngBind: <span ng-bind = "name"> </span></p> </body> </html> |
[sociallocker]
If you have read previous articles of angular JS series, I am sure you are already aware with this code. AngualrJS uses ng-bind for data binding, but we will use the expression {{expression}} instead ng-bind as such an approach is more intuitive to use and easy to remember.
OUTPUT:
AngularJS also provides several other data binding way:
- Simple Binding:
Here implements bind a simple addition operation which will show the binding between the ng-model and expression.It is known as data binding in Angular JS.
Let’s understand with the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> <html> <head> <script src="angular.min.js"></script> </head> <body> <div ng-app=""> <div> <input ng-model="num2" type="number" placeholder="Enter the numer"> <span>{{ num1+num2 || 0 }}</span> </div> </div> </body> </html> |
Here we have taken very simple example to give basic idea about data binding.ng-model is mainly for data binding that is inside the input type to bind the value and {{FiledName}} expression within double parentheses which is used to bind data.
Let’s see above code run time:
OUTPUT:
- $scope
$scope is an object used to bind the data through ng-model, in fact, so-called data binding is actually bound to the $ scope. Here in the following code, SumController method calculates the sum of two numbers when clicking on a button valued “sum”.
When you type something in the text boxes, a property named item is automatically added to the $scope.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE html> <html> <head> <script src="angular.min.js"></script> function SumController($scope){ $scope.addTwoNumber = function(){ $scope.addNumber = $scope.num2+$scope.num1; }; } </script> </head> <body> <div ng-app=""> <div ng-controller="SumController" > <input ng-model="num1" type="number" placeholder="Enter the number"> <input ng-model="num2" type="number" placeholder="Enter the numer"> <button ng-click="addTwoNumber()">Sum</button> <span>{{ addNumber||0 }}</span> </div> </div> </body> </html> |
Let’s see the above code run time:
- $apply()
We have seen in above mentioned method for data binding using $scope which is actually binding data to the ng-model. Simple clock procedures for updating every second clock values, we are mostly using setInterval method in Javascript whereas Here in Angular JS,we will use the apply method which is also a one of the data binding method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <!DOCTYPE html> <html> <head> <script src="angular.min.js"></script> <script type="text/javascript"> function CounterController($scope) { $scope.counter = 0; var updateCounter = function() { $scope.counter++; console.log($scope.counter); //log the data to observe }; var counter = 0; $scope.$apply(updateCounter); }, 1000); updateCounter(); } </script> </head> <body> <div ng-app=""> <div ng-controller="CounterController" > <h1>{{ counter }}</h1> </div> </div> </body> </html> |
OUTPUT:
setInterval call updateCounter () will print the current time every second, but the interface is not updated.Here setInterval will call $scope. $apply (updateCounter) will display once every one second of the current time, and update the interface.
Why is this? In fact, calling setInterval method cycle triggered by updateCounter methods.The native of setInterval JavaScript can not change the data monitored, so by $ apply to achieve.
- Angular Module
.net developers all know that in the development, will declare different namespaces and different classes to implement a modular management code. Such like Angular JS also offers a similar approach with ng-controller,ng-app and module managed code using the angular.module.
angular.module registered by a module in the background, and then to add the controller by app.controller. Here In following code we will use the two methos called ‘SumController‘ and ‘MultiplyController‘ which belongs to same application and $scope object bound the two functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!DOCTYPE html> <html> <head> <script src="angular.min.js"></script> <script type="text/javascript"> var app = angular.module('app', []); app.controller('SumController', function($scope) { $scope.addTwoNumber = function() { $scope.Totaladdition = $scope.num2 + $scope.num1; }; }); app.controller('MultiplyController', function($scope) { $scope.MultiplyTwoNumber = function() { $scope.TotalMultiplication = $scope.num2 * $scope.num1; }; }); </script> </head> <body> <div ng-app="app"> <div ng-controller="SumController"> <input ng-model="num1" type="number" placeholder="Enter the number"> + <input ng-model="num2" type="number" placeholder="Enter the numer"> <button ng-click="addTwoNumber()">Sum</button> <span>{{ Totaladdition||0 }}</span> </div> <br/> <div ng-controller="MultiplyController"> <input ng-model="num1" type="number" placeholder="input your number"> * <input ng-model="num2" type="number" placeholder="input your numer"> <button ng-click="MultiplyTwoNumber()">MultiPly</button> <span>{{ TotalMultiplication||0 }}</span> </div> </div> </body> </html> |
OUTPUT:
- ngBindHtml:
ngBindHtml (ng-bind-html) can be a string in a secure manner and is inserted into the page displayed as Html.
Let’s check the syntax used for ng-bind-html:
SYNTAX:
1 2 3 4 5 | <tag ng-bind-html="expression"> //desired code </tag> |
ngBindHtml will enforce the use of angular-sanitize service to perform safety checks and it is not included in the core library, you need to include angular-santitize.js external file and add the definition ngModule dependence for ngSantitize statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE html> <html> <head> <script src = "js/angular.js" > </script> <script src = "https://code.angularjs.org/1.2.1/angular-sanitize.js" > </script> <script type = "text / JavaScript" > (function() { var app = angular.module ( 'twowayBinding' , ['ngSanitize']); app.controller ('myController',['$scope', function ($scope) { $scope.myHtml = "This is a link: < a href = '#'>mylink</a>"; } ]); })(); </script> </head> <body ng-app = "twowayBinding" ng-controller = "myController" > <div> <span ng-bind-html = "myHtml" > </span> </div> </body> </html> |
OUTPUT:
As you can see in above code,’ngSanitize’ is passed with angular.module as the second parameter as ngModule dependent on the ngSanitize when using the ng-bind-html.
- ngBindTemplate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> <html> <head> <script src = "js/angular.js" ></script> </head> <body ng-app> Name: <input ng-model = "your_name" /> <br/> Occupation: <input ng-model = "your_occupation" /> <p> </p> </body> </html> |
OUTPUT:
ngBindTemplate (ng-bind-template) differs from the ngBind. ngBind is only a single bind variables and the variable without using double parentheses “{}”, while ngBindTemplate can bind a template and the template can include multiple AngularJS expressions with using double parentheses “{{expression}}”.
- ngNonBindable:
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE html> <html> <head> <script src = "js/angular.js" ></script> </head> <body ng-app> <div ng-non-bindable> This Will not be changed: {{1 + 2}} </div> </body> </html> |
However, if you have a content on your page with double parentheses like “{{my content}}” so such content will be compiled and replaced with value in AngularJS and using ngNonBindable (ng-non-binable), AngularJS will automatically ignore the content.
- Twoway Binding using ngModel:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <!DOCTYPE > <html> <head> <script src="/Scripts/angular.js"></script> <script type="text/javascript"> (function () { var app = angular.module('twowayBinding', []); app.controller('myController', ['$scope', function ($scope) { $scope.employees = []; $scope.addEmployee = function (emp) { $scope.employees.push(emp); $scope.emp = {}; }; $scope.employees.splice(index, 1); }; }]); })(); </script> </head> <body ng-app="twowayBinding" ng-controller="myController"> <div> <p>Name:<input ng-model="emp.name"></input></p> <p>Phone:<input ng-model="emp.phone"></input></p> <input type="button" ng-click="addEmployee(emp)" value="Add Employee" /> </div> <br/> <div ng-repeat="emp in employees"> <span ng-hide="editMode">{{emp.name}}</span> <input type="text" ng-show="editMode" ng-model="emp.name" /> <span ng-hide="editMode">{{emp.phone}}</span> <input type="text" ng-show="editMode" ng-model="emp.phone" /> <input type="button" value="Edit Employee" ng-hide="editMode" ng-click="editMode = true" /> <input type="button" value="Save Employee" ng-show="editMode" ng-click="editMode = false" /> <input type="button" value="Delete Employee" ng-hide="editMode" ng-click="removeEmployee($index)" /> <br/> </div> </body> </html> |
OUTPUT:
The above code shows AngularJS usage of two-way binding.Here We have used Edit, Save and Delete button which will work without any business logic. As it is Two-way binding,so when you enter the data into input and submit data,it will display data to the desired position using the $scope object which bind the value and amazing part is there is no different coding for Edit and Save.
Here we have used some new directives like ng-repeat,ng-show, and ng-hide.Let’s understand all of them below:
ng-repeat SYNTAX:
1 2 3 4 | <tag ng-repeat="(key, value) in myObj"> </tag> |
The ngRepeat directive is used when you’ve multiple values like array, object and you want to display as the loop.
ng-show/ng-hide SYNTAX:
1 2 3 4 5 | <tag ng-show="expression"> //desired code </tag> |
The ngShow directive is used to shows or hides the given HTML element.Here change the ng-show to ng-hide to hide the element.
As we have seen above, two-way data binding makes CRUD functionality very simple using Angular JS and without any business logic. Hope you are now clear with the data binding and directives in Angular JS.if you are not, copy the above examples, run and learn it :).We will explore other features of Angular JS in future series.
If you are unclear with above explanation or any query, write on the comment section. Where are you using Directives in AngularJS code? Share your knowledge 🙂
[/sociallocker]