Though the functionality of ngModel and ngBind attribute seems nearly same as both helps in binding data with element but there is a big difference between two. In actual both are totally alike to each other. ngModel enables two way binding between view and model whereas ngBind only helps in showing data on element. Use ngModel with controls like checkbox, text which has value attribute and use ngBind with elements like span or div which has text attribute.
If you are working with angularJS, you would be aware of ngModel and ngBind attributes. Both are very useful in getting/setting data in view. But sometime developer thinks both have similar functionality whereas in actual, it is not so. Both are totally different and has different functionalities. In this article we will go through few such differences between ngModel and ngBind.
We will discuss about these attributes one by one in below sections.
Main responsibility of ngModel or ng-model is to bind a control with model. It enables two way data binding i.e. from view to model and from model to view. Below code example shows how to use ng-model with an input tag. It binds Name model with input element and enables two way binding between input control and model.
<input type="text" ng-model="Name" />
In above code Name is the short way of $scope.Name
ngModel supports data validation as well as formatters. You can format your data before displaying it to users.
app.directive('testFormatter',function(){
return{
require:'ngModel',
link:function(scope,element,attrs,controller){
controller.$formatters.push(function(value){
return value.toUpperCase();
});
}
}
}
<input ngMode="Name" test-formatter/>
ngBind or ng-bind supports one-way data binding ( from $scope to view). It has a shortcut {{ ModelVariableName }} which displays the scope value $scope.VAriableName inserted into html. You should use ng-bind only where you need to display data.
Below line of code will bind Name model to span element and will enable one way binding.
<span ng-bind="Name"></span>
You can also use shortcut of ng-bind as {{Name}} instead of ng-bind="Name" or ng-bind="$scope.Name"
ngBind also supports filters means you can modify the data before displaying to users. In below code Name will be displayed in uppercase.
<div ng-bind="Name | uppercase"></div>
I think you have a good stuff now to start with. Hope this can help you. Please share and like the article and comment in below box with your suggestions or feedback.