Is it possible to add an ng-repeat $index value inside an ng-click with AngularJS?

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 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
   }
}

Method 2

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply