0

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

2

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

11 Comments

got it your answer is correct..but I am looking for using ng-class .Mean I want to write my logic o controller .I want to take one variable ..and that variable become true and false
your logic is fail when there 3 button ..and I want to do this only for first two button..it apply on all button
nope it'll work for all button though i have added your ngClass part @user944513
thanks i have one Question ..you are correct ...how vm is define in controller.we are not passsing to directive how vm.isLogin works.. see my plunker..plnkr.co/edit/Xw9ensF5zdnZv0rlE6I7?p=preview
I changed controllerAs: 'vmm', and ng-click='vmm.login()' ..but vm.login still work..why ? how directive knows it is true or false ..it is written in controller
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.