user2429448
user2429448

Reputation: 551

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.

Upvotes: 6

Views: 5503

Answers (3)

Golo Roden
Golo Roden

Reputation: 150782

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.

Upvotes: 7

Nat Wallbank
Nat Wallbank

Reputation: 1457

Doesn't this work?

ng-click="mnuClick(choice)"

I've definitely done something along those lines plenty of times, but don't have code to hand to verify...

Upvotes: 0

lex82
lex82

Reputation: 11317

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>

Upvotes: 2

Related Questions