NewToJS NewToJS - 2 months ago 17
AngularJS Question

Angular JS: Toggle 2 buttons with an ng-class

I have a button group where one button has the class "active" set by it's ng-class (myCtrl.onactive or myCtrl.offactive) to be true

<div class="btn-group pull-right">
<button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.changeColorIcons()">on</button>
<button ng-class="{active: myCtrl.offactive}" class="btn" ng-click="myCtrl.changeColorIcons()">off</button>

I'm trying to make whichever button is clicked to have the active class (and the other not)

So far I'm trying this in my controller (not working but this is what I'm going after), there must be a better way...

self.onactive = true; //by default the "on" button is active

//but when a button is clicked turn the one that's active off and make the other active
this.changeColorIcons = function() {
(self.onactive) ? self.offactive = true; self.onactive = false; : self.onactive = true; self.offactive = false;


Below is working code snippet, just simply add below function in your JS

var app = angular.module("app", []);
app.controller("Ctrl", ["$scope",
  function($scope) {

    var myCtrl = this;
    myCtrl.onactive = true;
    myCtrl.offactive = false;

  myCtrl.changeColorIcons = function(button) {

      if (button === 'on') {
        myCtrl.onactive = true;
        myCtrl.offactive = false;
      } else if ( button === 'off') {
        myCtrl.onactive = false;
        myCtrl.offactive = true;
.active {
  background-color: red;
<script src=""></script>
<div ng-app="app">
  <div ng-controller="Ctrl as myCtrl" class="btn-group pull-right">
    <button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.changeColorIcons('on')">on</button>
    <button ng-class="{active: myCtrl.offactive}" class="btn" ng-click="myCtrl.changeColorIcons('off')">off</button>