change classes with Angularjs

Asked

Viewed 3,664 times

1

I need to change the style of an element when clicked and if you click again it goes back to the color it was (as if it were an "advanced search"). I have the following code:

<a href="" class="corCinza" ng-click="exibirForm = !exibirForm">...</a>
<div class="filtro" ng-show="exibirForm">
    <form ... /> 
</>

When I click on <a> it has to stay with corazul and open the div with the form. If I click again it closes the div of the form and returns to corCinza. The form is already working, but I could not change the color. I tried to use ng-class as a "tutorial" but it didn’t work. Can someone help me? P.S.: I just "program" html and css. The most I coded was a simple helloWorld in JS.

1 answer

1


You can use the ng-class working with condition, changing the element class. Example:

<a href="" class="corCinza" ng-class="{'corAzul': !exibirForm}" ng-click="exibirForm = !exibirForm">

When exibirForm for false, the class corAzul will be added.

You can also use with more than one class definition if you want to remove the existing class, for example:

<a href="" ng-class="{'corCinza': exibirForm, 'corAzul': !exibirForm}" ng-click="exibirForm = !exibirForm">

This way it only displays one class at a time.

  • Our @Celsomtrindade, I was thinking of "more complex" solutions. That worked great. Thank you!

  • Not so ;) Just remember: class defined within class="" is static, cannot be removed through the ng-class. Class defined within the ng-class="" will only be added to class="" if the condition confers.

  • Ook!! Thanks again! D

  • @trofonia if solved the problem, do not forget to mark the answer as accepted =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.