Difference between ngBind, ngBindHtm and ngBindTemplate in Angular JS
ng-bind
ng-bind binds the value of a variable or expression to an HTML element i.e the content of HTML element is replaced with the value of a variable or expression when ng-bind is used.
For e.g:
Within Angular JS Controller when a variable is initialized as follows:
$scope.firstname = Deepak
The above variable value can be binded to an HTML element through ng-bind:
<p ng-bind = firstname></p>
The above expression will be converted into
<p>Deepak</p>
But this directive cannot be used to bind values of various variables in a single HTML element.
For e.g:
Two variables initialized within Angular JS controller:
$scope.firstname = Deepak
$scope.lastname = Negi
The above two variables if used in single HTML element like
<p ng-bind = firstname lastname></p>
This expression will only bind the value of first variable used i.e value of firstname and thereby converting the expression into <p>Deepak</p>.
ng-bind-template
The ng-bind-template directive binds the value of multiple variables to a single HTML element.
For e.g:
Two variables initialized within Angular JS controller:
$scope.firstname = Deepak
$scope.lastname = Negi
The above two variables when used in single HTML element with ng-bind-template like
<p ng-bind-template = firstname lastname></p>
Then this expression will be converted into <p>Deepak Negi</p> displaying Deepak Negi on screen.
ng-bind-html
The ng-bind-html directive not only bind values of a single or multiple variables to a single HTML element but also allows rendering of HTML element used as part of value of variable, this HTML tag rendering is not allowed in ng-bind or in ng-bind-template.
For e.g:
Within Angular JS Controller when variables is initialized as follows:
$scope.firstname = <b>Deepak</b>
$scope.lastname = <b>Negi</b>
The above two variables when used within HTML element with ng-bind-html like
<p ng-bind-html = firstname lastname></p>
Then this expression will be converted into <p><b>Deepak</b><b> Negi</b></p>, rendering <b> html tag displaying Deepak Negi in bold within a paragraph on screen.
If above variable were used like
<p ng-bind-template = firstname></p>
or
<p ng-bind = firstname></p>
Then both will display <b>Deepak</b> on screen not rendering the HTML tag used as part of value of variable.
Based on above scenarios these three directives can be used according to the requirements.
0 Comment(s)