0

I have this in my app:

<li ng-repeat="name in tabs track by $index" ng-class="{selected: tab==$index}" ng-click="tab = $index">{{name}}</li>

and it don't work, selected class is enabled when I click on the item (each li I click have this class and it's not removed when I click other li) and tab is not updating, it work when I use this:

<li ng-repeat="name in tabs track by $index" ng-class="{selected: tab==$index}" ng-click="switchTab($index)">{{name}}</li>

scope.switchTab = function(index) {
  scope.tab = index;
};

why is this happening, why ng-click="tab = $index" don't work?

2
  • Are you able to get index argument inside controller function? Commented Jan 10, 2017 at 11:06
  • @DhavalMarthak it was a typo it should be scope.tab = index; Commented Jan 10, 2017 at 11:41

1 Answer 1

5

You have a typo, change to:

scope.switchTab = function(index) {
  scope.tab = index;
};

You used $index even though the parameter in your function is index.

Edit: The reason it works with a function and not an assignment directly, is that ng-repeat creates a new scope. When you do: tab = $index you create a new variable on that new scope, rather than updating the one on the $scope you think.

See this question for further in-depth info.

Sign up to request clarification or add additional context in comments.

1 Comment

It was a typo when I added the code, the question was why ng-click="tab = $index" don't work, switchTab is working.

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.