Data binding is the connection between the source of data and the consumer.AngularJS takes care of lot of data binding features by default.
Two of the main data binding directives are ng-model and ng-bind.Both are used for data binding.
What is the difference between ng-bind and ng-model in AngularJs
ng-model
ng-model is used for binding the view to the model.You bind the input fields in the view to the model.Whenever the value in the input field changes,value in the underlying model also changes.It provides two way data binding.
We can use ng-model directive in our view as:
<textarea ng-model="propertyName"></textarea>
The propertyName above can be replaced with any valid property name defined in $scope.So if you want to bind with the empName property then you can declare textarea as:
<textarea ng-model="empName"></textarea>
In the controller you can add empName as:
$scope.empName="John";
ng-model is used inside input field such as textbox,checkbox etc.
ng-bind
ng-bind is also used for data binding but unlike ng-bind it supports only one way data binding.It is used for displaying model properties as innerHTML of html elements such as div and span.This is unlike ng-model which is used for binding input fields and supports two way data binding.
When the value in the scope changes it is reflected in the view.
You can use ng-bind as:
<div ng-bind="propertyName"></div>
So if you want to display the property empName in your view then you can use ng-bind as:
<p ng-bind="empName"/>
ng-model example
If you run the following example you will see that change in ng-model are reflected in the underlying model property in controller:
<html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <div ng-app="simpleApp" ng-controller="simpleController"> Emp Name <input ng-model="name"> Hello {{name}} </div> <script> var app = angular.module('simpleApp', []); app.controller('simpleController', function($scope) { $scope.name = "John Doe"; }); </script> </body> </html>
Leave a Reply