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?

jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

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.

Community
  • 1
  • 1
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • It was a typo when I added the code, the question was why `ng-click="tab = $index"` don't work, switchTab is working. – jcubic Jan 10 '17 at 11:40