3

I am trying to make HTML headings active/inactive based on active variable. But to set the active flag on clicking the heading, I am using the $index variable of ng-repeat directive:

<div ng-init="active = 1">
  <h4 ng-repeat="(key, val) in vm.headings" ng-click="active = $index" ng-class="{'active': active === $index}">
{{key}}
</h4>
</div>

Heading object:

vm.headings = {
    "HEADING_1": "CONTENT",
    "HEADING_2": "CONTENT",
    "HEADING_3": "CONTENT"
};

On first load, one of the headings appear 'active` as set. But on subsequent clicks, it does not give the desired results. All the headings become active on clicking them. Here is the fiddle.

Rishabh
  • 900
  • 10
  • 30

1 Answers1

5

Try this:

<h4 ng-repeat="(key, val) in vm.headings" ng-click="selectH($index)" ng-class="{'active': active === $index}">

In controller:

$scope.selectH= function(index) {
   $scope.active = index; 
};

Hope this will work.

Avnesh Shakya
  • 3,828
  • 2
  • 23
  • 31
  • For more details on the problem: http://stackoverflow.com/questions/17925355/how-can-i-use-the-index-inside-a-ng-repeat-to-enable-a-class-and-show-a-div – Dese Dec 28 '16 at 09:13