Zanon
Zanon

Reputation: 30790

Trailing double quotes in AngularJS expressions

I've found this highly upvoted answer (+50) and this comment suggesting that ending an expression with a semicolon and double quotes, i.e. ;"", could be used when you want to define an Angular variable in your template without rendering it as text.

I've tested and it works. Example:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="">
  <p>This variable is rendered: {{ text1 = 'yes' }}   </p>
  <p>This variable isn't:       {{ text2 = 'yes';"" }}</p>  
</div>

I know that using ngInit is the best approach to initialize a variable, but +50 users upvoted the other suggestion and I'm wondering: is this a documented feature? I could not find any reference to this.

If it isn't a feature and rather a rendering bug that people are taking advantage of, should I assume that it isn't safe to use and likely to be fixed in the future?

Upvotes: 2

Views: 499

Answers (1)

georgeawg
georgeawg

Reputation: 48968

It is not a rendering bug. When multiple expressions are separated by a semicolon the Angular expression evaluates to the last expression.

 {{a=5; x=4; z="hello"}} evaluates to {{"hello"}}

 {{ text2 = 'yes';"" }} evaluates to {{""}}

An empty string is not rendered.

That behavior is not going to go away.

Upvotes: 3

Related Questions