Shamoon Shamoon - 4 months ago 4
AngularJS Question

How do I add a class on click to a parent element in AngularJS?

My HTML is as follows:

<div class="cell">
<div class="offset-container pull-left">
<i data-ng-click="doCtrlStuff()"></i>
</div>
</div>


When you click the
<i>
, I want to add an
active
class to the parent that has
.cell
currently. How is this doable with AngularJS?

Answer

OK, according to your last comment, if your cells are in a loop you should have mentioned that in your question. I'm gonna assume you use ng-repeat.

I have something like this which works. The active class also get removed if you click another.

HTML:

<div ng-repeat="cell in [0,1,2]" data-ng-class="{cell:true, active:index=='{{$index}}'}">
    <div class="offset-container pull-left">
        <i data-ng-click="activate('{{$index}}')">Activate Me</i>
    </div>
</div>

Controller:

  $scope.activate= function(index){
      $scope.index=index;
  };
Comments