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

2 Answers 2

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
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.