Learn about Dynamically Changing Classes in AngularJS

0
3766
Dynamically-changing-classes

Dynamically-changing-classes

One of the many strengths of Angular is the directives. They allow us to easily change the DOM and bind Angular functionalities to elements, as we specify. In this tutorial, we’re going to make use of the ng-class directive, which has multiple uses, such as tying classes to elements dependent on dynamic conditions and changing elements’ classes depending on variables or expressions.

We’re now going to go over an example in which we dynamically change the class of an element. Let’s start by creating a select box with different options. We’re going to change the class of an element using a select box. Let’s start with the HTML:

The CSS:

We’re now going to add a new text paragraph and give the ng-class directive the value of textS.

So, whatever value we assign to textS in the select box or if we change the value of ng-model in any way, we automatically reference it in the ng-class directive and use it to automatically change the class of the element ng-class sits inside.

https://blogeduonix-2f3a.kxcdn.com/wp-content/uploads/2015/10/Learn-Javascript-And-JQuery-From-Scratch.png

In our next example, we’ll see how to selectively bind different classes to even or odd elements. For this purpose, we’ll create a variable which is an array of objects containing index-value pairs:

Next, inside our controller, we’re going to create a table and then cycle through our array items using the ng-repeat directive.

Explanation: Locations is the name of our array, therefore we apply ng-repeat on ‘x in locations’. We used the ng-class-odd/even directives to bind classes to the even and odd elements. The class names appear in double quotes. Thus, the script in this case is complemented by CSS:

We’ll finish off with a practical example of what ng-model can be used for in dynamic website forms.

Additionally, we’ll ask the user to let us know his eye size. For that purpose, we’ll use check-boxes, like so:

A class will be added to a div element, based on the user’s choice.

Explanation: We are using curly brackets to tell Angular that this is an expression to be evaluated. We put the class that will be added to the left of the colon, and the

variable to be evaluated to the right of the colon. All we need now is the CSS:

angularIn summary, Angular directives allow us to easily change the DOM and bind Angular functionalities to elements. In this tutorial, we’re used ng-class, ng-class-even/odd and ng-model to bind classes to elements dependent on dynamic conditions and change elements’ classes depending on variables or expressions.

LEAVE A REPLY

Please enter your comment!
Please enter your name here