10

Please help me to change the class of input[type=button] dynamically using angularjs and controller.

app.controller('anodekeypadcntrl',function($scope){
	
	
	$scope.clickTwentyFour = function(event){
	  In this function I need to highlight the button (adding the .active class to it)	
	};
	                            
});
<div class="keypadcontainer" ng-controller="anodekeypadcntrl as child">
  ------
  <input type="button" value="24" id="twentyFour" class="twentyfour anodeKeypadButton"
	ng-click="clickTwentyFour($event)" />
  -------------
</div>

4 Answers 4

17

You can use ngClass for this. In your markup just do something like:

<input type="button" value="24" id="twentyFour" class="twentyfour anodeKeypadButton"
ng-click="clickTwentyFour($event)" ng-class="myDynamicClass" />

This way you can set myDynamicClass to be either a single string containing a CSS class or an array of strings directly from your controller

// controller code
$scope.myDynamicClass = 'some-css-class';

This will get appended to the HTML. If you look at the ngClass docs you will see that you can even attach functions which return a class, or write the classes directly in the HTML with conditions attached.

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

Comments

5

If you want to add class then Try this :

var myEl = angular.element( document.querySelector( '#twentyFour' ) );
myEl.addClass('active'); 

you can replace the the things in the querySelector with your required id.

2 Comments

Although this is a perfectly fine method, we wouldn't want to reinvent the wheel here. Angular already provides built-in functionality for setting dynamic classes and styling so we shouldn't complicate our code with selectors and such.
Thats true but there is no clear explanation or case how the button should have an active class so question will have this simple answer.if it was more specific dynamic binding of the class would be a better option
3

You can use ng-class to dynamically add class to your divor button or whatever

Here is a working plunker with your code

http://embed.plnkr.co/rzS8GV975BHRk83xhsPx/preview

Hope this helps

Comments

-1

You can do that by using 'ngClass'. Also note that you can use a expression to decide the class of any html element.

Suppose there is a model element named $isButtonActive=false;

    <input type="button" value="24" id="twentyFour" class="twentyfour anodeKeypadButton" ng-click="clickTwentyFour($event)"
 data-ng-class="isButtonActive? 'Active': 'Passive' "/>

By changing the value of the 'isButtonActive' from controller, (isButtonActive value to 'true', the 'Active' class is added) you can control the css class.

Comments

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.