Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply CSS class on HTML element inside ng-repeat based on condition [duplicate]

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.

like image 268
Rishabh Avatar asked Apr 16 '26 01:04

Rishabh


1 Answers

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.

like image 153
Avnesh Shakya Avatar answered Apr 17 '26 16:04

Avnesh Shakya