Shamoon
Shamoon

Reputation: 43491

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?

Upvotes: 5

Views: 8572

Answers (4)

NicolasMoise
NicolasMoise

Reputation: 7279

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;
  };

Upvotes: 6

programmerdave
programmerdave

Reputation: 1238

You can do this from here: http://docs.angularjs.org/api/ng.directive:ngClass

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

You would use a class:boolean pattern for the ng-class expression.

And in your controller:

$scope.doCtrlStuff = function() {
    $scope.clickedIcon = true;
}

UPDATE:

If you want to do a radio button:

<div data-ng-class="{cell:true, active:clickedDogIcon}">
  <div class="offset-container pull-left">
    <i data-ng-click="doDogStuff()"></i>
  </div>
</div>
<div data-ng-class="{cell:true, active:clickedCatIcon}">
  <div class="offset-container pull-left">
    <i data-ng-click="doCatStuff()"></i>
  </div>
</div>

$scope.doDogStuff = function() {
    $scope.clickedDogIcon = true;
    $scope.clickedCatIcon = false;
}
$scope.doCatStuff = function() {
    $scope.clickedDogIcon = false;
    $scope.clickedCatIcon = true;
}

Upvotes: 0

kmdsax
kmdsax

Reputation: 1361

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;
    }             
}

Upvotes: 2

Max
Max

Reputation: 1150

<div class="cell" ng-class="{'active': isActive}">
  <div class="offset-container pull-left">
    <i data-ng-click="isActive = !isActive"></i>
  </div>
</div>

Upvotes: 0

Related Questions