8

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.

Jacob Sievers
  • 467
  • 4
  • 12
  • possible duplicate of [Are complex expressions possible in ng-hide / ng-show?](http://stackoverflow.com/questions/15166184/are-complex-expressions-possible-in-ng-hide-ng-show) – bransonl Sep 03 '15 at 13:23
  • I'm more interested in how this works with HTML not allowing use of '&' except for HTML character entities. – Jacob Sievers Sep 03 '15 at 13:34
  • 1
    Thymeleaf gives a SAXParseException while using them. So you shouldn't use them if you're also using Thymeleaf. – cst1992 Oct 27 '16 at 06:17

3 Answers3

4

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:

Adam Tolley
  • 865
  • 1
  • 12
  • 21
rjh
  • 46,345
  • 3
  • 47
  • 60
2

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...

-1

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/

Mathew Berg
  • 26,908
  • 11
  • 66
  • 86