Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 898
Shamoon Avatar asked Oct 04 '13 15:10

Shamoon


2 Answers

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;
  };
like image 175
NicolasMoise Avatar answered Nov 01 '22 16:11

NicolasMoise


Here is one way, using ng-class

<div class="cell" ng-class="{'active': isActive==true}">
  <div class="offset-container pull-left">
    <i data-ng-click="doCtrlStuff()">clicky</i>     
  </div>
</div>

controller:

function MyCtrl($scope) {
    $scope.doCtrlStuff = function(){
        $scope.isActive = true;
    }             
}
like image 27
kmdsax Avatar answered Nov 01 '22 15:11

kmdsax