how to add class on button click in angular?

Ad

I make a simple directive .I have two button on that directive .I am able to get click event of that button .But I want to add class on that .

I have one class

.red {
  background-color: red;
}

I want to add this class whenever button is click ..

  • Intially login button have red class .When logout button is click it apply on logout button and remove from login button

or again if I click on login button it apply on login button and remove from logout button ..

I do like that

angular.module('app', ['ui.router']).directive('tm', function() {
  return {
    restrict: 'E',
    templateUrl: 'login.html',
    scope: {
      login: "&",
      logout: '&'
    },
    controller: 'f',
    controllerAs: 'vm'
  };
})

here is code http://plnkr.co/edit/Q1e8u0okOa4looLcb2YO?p=preview

Ad

Answer

Ad

Add a link function

Try like this

link: function(scope, elm, attr) {
  elm.find("button").on("click", function(e) {
    elm.find("button").removeClass("red");
    angular.element(this).addClass("red");
  })
}

PLNKR

Or you can do it using ngClass

Like this

JS

vm.isLogin = true;
vm.login = function() {
  vm.isLogin = true;
}

vm.logout = function() {
  vm.isLogin = false;
}

HTML

<button type="button" class="btn btn-default"  ng-class="{'red': vm.isLogin }"  ng-click='vm.login()'>Login</button>
<button type="button" class="btn btn-default" ng-class="{'red': !vm.isLogin }" ng-click='vm.logout()'>logount</button>

PLNKR

Ad
source: stackoverflow.com
Ad