Difference between ngBind, ngBindHtm & ngBindTemplate in Angular JS [closed]
Asked Answered
M

2

23

I'm new to Angular JS.

Can any one of you guys explain me the difference between ngBind,ngBindHtm & ngBindTemplate in Angular JS with an example?

Mavis answered 13/1, 2014 at 4:41 Comment(2)
RTFM. docs.angularjs.org/api/ng.directive:ngBind docs.angularjs.org/api/ng.directive:ngBindHtml docs.angularjs.org/api/ng.directive:ngBindTemplateRemains
I'm confused with what they say in Angular DocsMavis
A
46

ng-bind

ngBind is used to replace the text content of the specified HTML element with the value of a given expression. For example if you have an html as follows <b ng-bind="name"></b> and in your controller give a value for name as $scope.name = "John". This will result in <b>John</b>. But you can't use multiple values to bind in a single html element. For example

$scope.first_name = "John";
$scope.second_name = "D";
<b ng-bind="first_name second_name"></b> 

This will not give the result as <b>John D</b> only bind first_name. So for binding multiple values we can use ng-bind-template

ng-bind-template

 $scope.first_name = "John";
 $scope.second_name = "D";

<b ng-bind-template="{{first_name second_name}}"></b>

This results in <b>John D</b> But you can't render an html tag in this both. For rendering html template we can use ng-bind-html.

ng-bind-html

$scope.name = "<b>John</b>";
<div ng-bind-html="name"></div>

This will result in John instead of showing <b>John</b> . That means it renders the html instead of showing html tag.

Click this link to view example

Aweigh answered 13/1, 2014 at 8:28 Comment(3)
<b ng-bind="first_name + ' ' + second_name"></b> is working. We can make ng-bind work like ng-bind-template, but need to do some ugly work. Thats it?Mongolic
I see, the real difference is we can use one or more {{ expression }} in ng-bind-template, while in ng-bind we cannot.Mongolic
@jilykate You can use it like ng-bind="(person.firstName)+ ' ' +(person.lastName)"Amari
O
3

ngBind :

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

ngBindTemplate :

The ngBindTemplate directive specifies that the element text content should be replaced with the interpolation of the template in the ngBindTemplate attribute. Unlike ngBind, the ngBindTemplate can contain multiple {{ }} expressions. This directive is needed since some HTML elements (such as TITLE and OPTION) cannot contain SPAN elements. ngBindTemplate only runs "strings"

A simple metaphor for the difference:

ngBind only runs "objects".

ngBindTemplate only runs "strings"

Odilo answered 13/1, 2014 at 5:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.