0

In my HTML I have a dropdown list that I did with an ng-repeat. Each of these elements needs to have their own function when clicked, so I'm using $index. Here's part of my code:

<div class="dropdown-menu status-menu" aria-labelledby="dropdownMenuButton">
   <span class="dropdown-item active" ng-click="allItems()">All Items</span>
   <span ng-repeat="x in itemsArray" class="dropdown-item"
         ng-click="myFunction{{$index}}()">{{x.name}}</span>
</div>

When I inspect the element in the browser, it actually shows the items like this:

ng-click="myFunction0()", ng-click="myFunction1()", ng-click="myFunction2()", etc...

But when click on them, they don't work, and the console throws this error:

Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 11 of the expression [myFunction{{$index}}()] starting at [{{$index}}()]

Got any idea on how can I make this work, or if there is a better approach?
Thanks in advance

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Soul Eater
  • 505
  • 1
  • 7
  • 20

2 Answers2

1

Also you can solve it by pass index in one function:

HTML:

<div class="dropdown-menu status-menu" aria-labelledby="dropdownMenuButton">
   <span class="dropdown-item active" ng-click="allItems()">All Items</span>
      <span ng-repeat="x in itemsArray" class="dropdown-item" 
            ng-click="myFunction($index)">{{x.name}}</span>
</div>

Controller:

$scope.myFunction(index){
   switch(index){
     case 0: 
        ///function 0
     break;
     case 1:
        ///function 1
     break;
     //etc
   }
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Maher
  • 2,517
  • 1
  • 19
  • 32
0

Don't use interpolation ({{ }}) inside AngularJS expressions. Instead use a property accessor:

<div class="dropdown-menu status-menu" aria-labelledby="dropdownMenuButton">
   <span class="dropdown-item active" ng-click="allItems()">All Items</span>
   <span ng-repeat="x in itemsArray" class="dropdown-item"
         ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶m̶y̶F̶u̶n̶c̶t̶i̶o̶n̶{̶{̶$̶i̶n̶d̶e̶x̶}̶}̶(̶)̶"̶
         ng-click="this['myFunction'+$index]()">
     {{x.name}}
   </span>
</div>

With AngularJS expressions, the this context is bound to $scope.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95