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");
})
}
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>
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad