Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't use angular value within quotes

Why does this not work:

<ul class="dropdown-menu">
  <li ng-repeat="choice in dropDownItems">
    <a class="btn" ng-click="mnuClick('{{choice}}')">{{choice}}</a>
  </li>
</ul>

But this does work:

<ul class="dropdown-menu">
  <li ng-repeat="choice in dropDownItems">
    <a class="btn" ng-click="mnuClick('xxx')">{{choice}}</a>
  </li>
</ul>

In the top example, the mnuClick() routine never gets called, but in the bottom example, it does. When I do an 'inspect element' everything looks fine.

like image 578
user2429448 Avatar asked Dec 11 '13 20:12

user2429448


2 Answers

It does not work, because the way you did it you are saying that you want to provide the string {{choice}} to the mnuClick function.

When providing xxx, this is actually correct, hence you need the quotes here.

But when using {{choice}}, you don't want THAT string, but you want that expression to be evaluated and its result (which is probably a string) as a parameter - hence you don't need the quotes (and not even the curly braces) here.

So just write

<a class="btn" ng-click="mnuClick(choice)">{{choice}}</a>

and you're fine :-).

To cut it short: In one case you deal with an expression which resolves to a string, in the other case you deal with a string directly. Hence one time you don't need quotes, the other time you do.

If you want more detailed information on when to use curly braces and when not, check out this answer to this question: Difference between double and single curly brace in angular JS?

Hope this helps.

PS: Inside the text of your a tag, you need the double curly-braces, as you're not in a AngularJS controlled code-block here - hence you have to mark it as binding, otherwise it'd just be text inside of HTML.

like image 149
Golo Roden Avatar answered Nov 07 '22 01:11

Golo Roden


The value of ng-click is interpreted as an angular expression so you don't have to use the curly brackets around "choice". Just write it like this:

<a class="btn" ng-click="mnuClick(choice)">{{choice}}</a>
like image 2
lex82 Avatar answered Nov 07 '22 00:11

lex82