ng-bind-html vs {{interpolation}}
Asked Answered
C

2

6

That is my question, what are the pros and cons ?

In my app I am using interpolation but I get errors like this

{{::sport.name}} -> NHL Futures & Props

and if I use ng-bind-html

ng-bind-html="sport.name" -> NHL Futures & Props

in this case ng-bind-html is doing what I want. But, is there something wrong with it ?

Is there one better than the other ?

so tell me, I am open to suggestions.

Contrapositive answered 13/5, 2015 at 14:4 Comment(7)
ng-bind-html is used to interpret html instead of just displaying the textual content of your variable. {{<b>hi</b>}} will display "<b>hi</b>" but ng-bind-html="<b>hi</b>" will display a bold hi.Undergrowth
@Undergrowth why not post that as an answer?Draft
@Undergrowth hey, but explain a little more, is there something with the performance ? why one is better than the other ?Contrapositive
@NietzscheProgrammer ng-bind-html sanitize the html using $sce while ng-bind don't sanitize html..Both are used for different purpose..so we can't compare them on basis of their performanceIdea
@Pureferret wasn't sure it was an answer to the question. Should i ?@NietzscheProgrammer I don't have this knowledge, but in my opinion ng-bind-html should be used only on purpose, when you want some HTML in a variable to be interpreted. In your case this is just a workaround to solve your problem.Undergrowth
@Undergrowth I definitely think so. If you wanted to dig into performance, it can be edited in later. But as it stands it sounds pretty complete.Draft
Look back to the question a few days ago where you found out about ng-bind-html and why you started using it in the first place. text vs htmlUnharness
U
6

Actually the main difference between ng-bind and ng-bind-html is the usecase. ng-bind will just display the text interpretation of your variable but ng-bind-html will interpret the html in your variable.

Let say we have a variable in your scope

 $scope.myText = "<b>Hi</b>";

ng-bind or {{}} would display

 <b>Hi</b>

ng-bind-html would display

Hi

Another precision is that ng-bind-html can sanitize your html to prevent code injection.

Undergrowth answered 13/5, 2015 at 14:33 Comment(0)
C
2

ng-bind-html under the covers uses $element.html to set the content (after it is either explicitly trusted or sanitized)

{{ }} (or the equivalent ng-bind) uses $element.text (actually $element[0].textContent) to set the content.

So, in other words - the first sets the HTML and the second one sets Text content. That is why you are seeing the difference with &amp;.

Compartmentalize answered 13/5, 2015 at 14:21 Comment(1)
Another important distinction between ng-bind and {{}} is that the former allows more control over what your page looks like before Angular loads (if it ever does).Tyrosine

© 2022 - 2024 — McMap. All rights reserved.