xdfil
xdfil

Reputation: 291

How to change CSS class of HTML element from inside AngularJS controller logic

I'm looking for an example to change CSS class of an HTML element from inside the logic of the AngularJS controller

In the controller, something like this:

function myFunc() {
  //do a calculation
  //result is 3
  //change the class of HTML element with id="3" to add class="hidden"

I can't do it with ngClick because the controller decides which element to change, not the user.

Like if I wanted to recreate that Simon game from the 80's I would have the controller pick a random number 1-4 and then light up the HTML element and the user would have to click it in a certain amount of time.

choice = Math.floor(Math.random() * 4) + 1;
if ( choice == 2 ) {
  lightUpBlue();
  setTimeout(turnOffBlue();, 2000);
}

How would I write lightUpBlue() to change the color of a button in the HTML document, and maybe change the hyperlink or some other property?

Thanks in advance.

Upvotes: 0

Views: 2440

Answers (3)

xdfil
xdfil

Reputation: 291

ngShow Looks like the best solution for hiding an element.

Upvotes: 0

Shashank Agrawal
Shashank Agrawal

Reputation: 25817

Best practice is to avoid manipulating DOM element from inside controllers or services. For this you can write a custom directive.

Well you can modify any of the element like:

angular.element(document.querySelector('[id="3"]')).addClass('hidden');

Upvotes: 1

Luba
Luba

Reputation: 495

Use ng-class inside your html code.

HTML for Elements

ng-class="myFunction"

Documentation for ng-class

Controller

scope.myFunction = function() {
}

Documentation for controller
Documentation for scopes

Upvotes: 1

Related Questions