Search code examples
javascriptangularjsangularjs-ng-click

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


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


Solution

  • 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