noob-fella noob-fella - 5 months ago 11
AngularJS Question

Angular.js How to insert css class on click and to remove all others

I'm applying two css classes onto my html, when I click on my span element.

right now I have a border and looks fine, I want keep this.

but:
so If I click in the Icon I said in the icon

<i>
the Icon color change for blue.

but I don't want remove the functionality of the span who contains the border.

thanks.

html + angular

<div ng-app>
<div>
<br>
<i ng-class='{"gamepad-red":tog==1}' class="fa fa-lg fa-gamepad"></i>
<span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
</div>

<div>
<br>
<i ng-class='{"gamepad-red":tog==2}' class="fa fa-lg fa-gamepad"></i>
<br/><span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>
</div>
</div>


css:

.myclass {
border: dotted pink 3px;
}

.gamepad-red {
color: red;
}

.gamepad-blue {
color: blue;
}


jsfiddle: http://jsfiddle.net/zvLvg/286/

Answer

I have moved the effect of the span click to the wrapping div and used parent-child CSS to apply the red to the i element.

On click of the icon it triggers a separate boolean that controls a local class

iTog1 and iTog2 can be made to behave similar to tog if there can only be one selected

.selected-gamepad > span {
  border: dotted pink 3px;
}

.selected-gamepad > i {
  color: red;
}

.gamepad-blue,
.selected-gamepad .gamepad-blue{
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

<div ng-app>
  <div ng-class="{'selected-gamepad':tog==1}">
    <br>
    <i class="fa fa-lg fa-gamepad" ng-class="{'gamepad-blue': iTog1}" ng-click="iTog1 = !iTog1"></i>
    <span id='1' ng-click='tog=1'>span 1</span>
  </div>

  <div ng-class="{'selected-gamepad':tog==2}">
    <br>
    <i class="fa fa-lg fa-gamepad"  ng-class="{'gamepad-blue': iTog2}" ng-click="iTog2 = !iTog2"></i>
    <span id='2' ng-click='tog=2'>span 2</span>
  </div>
</div>