admin管理员组

文章数量:1323323

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.

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.

Share edited Apr 11, 2019 at 14:54 Jacob Sievers asked Sep 3, 2015 at 13:21 Jacob SieversJacob Sievers 5344 silver badges14 bronze badges 3
  • possible duplicate of Are plex expressions possible in ng-hide / ng-show? – bransonl Commented Sep 3, 2015 at 13:23
  • I'm more interested in how this works with HTML not allowing use of '&' except for HTML character entities. – Jacob Sievers Commented Sep 3, 2015 at 13:34
  • 1 Thymeleaf gives a SAXParseException while using them. So you shouldn't use them if you're also using Thymeleaf. – cst1992 Commented Oct 27, 2016 at 6:17
Add a ment  | 

3 Answers 3

Reset to default 5

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:

  • https://www.w3/TR/html5/syntax.html#escapable-raw-text-elements
  • https://www.w3/TR/html5/syntax.html#syntax-ambiguous-ampersand

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

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/8drnp4ue/

本文标签: javascriptIs it safe to use ampersands (amp) in AngularJS html templatesStack Overflow