Jacob Sievers
Jacob Sievers

Reputation: 534

Is it safe to use ampersands (&) in AngularJS html templates

I have been told that using ampersands in angular templates is bad practice since '&' is reserved in HTML, but I see it in examples for angular all the time.

To be clear, would it be safe to write

<div ng-show="bool1 && bool2"></div>

in an angular template?

I'm not interested in knowing if it works (it does), but if there are any edge cases where this could cause problems or if it's in fact discouraged.

Upvotes: 8

Views: 3708

Answers (3)

rjh
rjh

Reputation: 50304

It's fine. The HTML5 spec explicitly allows unencoded ampersands if they don't look like a character reference (such as &copy;). Sure, for some things like URLs it's better to be consistent and escape them. But for && with spaces around it, there's no chance that the browser will misinterpret the data, and &amp;&amp; is significantly less readable.

Relevant Sections of the spec:

Upvotes: 5

Mathew Berg
Mathew Berg

Reputation: 28750

Yes that is just fine, I use it all the time. Here's a fiddle showcasing:

 <div data-ng-show="bool1 && bool2">bool1 && bool2</div>
 <div data-ng-show="bool1 && !bool2">bool1 && !bool2</div>
 <div data-ng-show="!bool1 && bool2">!bool1 && bool2</div>
 <div data-ng-show="!bool1 && !bool2">!bool1 && !bool2</div>

http://jsfiddle.net/8drnp4ue/

Upvotes: -1

FullyHumanProgrammer
FullyHumanProgrammer

Reputation: 101

I use ampersands in my Angular html templates too and never had a problem with them, but the best way to see if it's safe for you to use them is to just test their effect in a test app that resembles yours I guess...

Upvotes: 2

Related Questions