Dynamically apply a class using AngularJS

Angular provides ng-class directive for adding/removing css styles dynamiucally.

According to angular docs: The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

ng-class accepts an "expression" that must evaluate to one of the following:

1.a string of space-delimited class names
2.an array of class names
3.a map/object of class names to boolean values

Lets say you are showing a list of items using ng-repeat and each item has a corresponding checkbox. Now when a checkbox is checked then you want to apply some styles to that respective item (like changing the color etc). This can de done using ng-class. Look at the below code to see how it works.

Example:

html code:

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items" ng-class="{'selected-item': item.checked}">
        <input type="checkbox" ng-model="item.checked">
        {{item.name}}{{item.title}}
    </div>
</div>

javascript:

var myApp = angular.module('myApp', []);
 
function MyCtrl($scope) {
    $scope.items = [
        {
            name: 'Misko',
            title: 'Angular creator'
        },
        {
            name: 'Igor',
            title: 'Meetup master'
        },
        {
            name: 'Vojta',
            title: 'All-around superhero'
        }
 
    ];
}

css:

.selected-item {
    colorgreen;
}


When you click on a checkbox, the class "selected-item" gets added to the particular item and the color will be changed to green as mentioned in css.

For live example look at this fiddler: http://jsfiddle.net/codingsolver/dxBdR/

Note: If a class was already applied then the directive will not add duplicate class. When expression changes , newly added classes will be removed.

This way we can add css classes dynamically using AngularJS.

For more posts on AngularJS visit: AngularJS

No comments:

Post a Comment