AngularJS > CSS Class & Style

ng-style in AngularJS

How to set CSS style using AngularJS?


In some cases, we might need to set CSS style of a particular element using AngularJS, for this we can use ng-style (ngStyle) directive. Let's see how to work with ng-style directive.

In below code snippet, we have a app and controller defined. In the controller we have defined CustomStyle object, BColor (for background) and Color (for text color) properties. These properties deault value are set so that it would appear in the drop down.

In the SetStyle function, we have set the CustomStyle object value with BColor (for 'background-color') and Color (for 'color') properties value separated by comma. These values comes from respective drop down value selected by user.

<script>
    var app = angular.module("app", []);
    app.controller("StyleController", function ($scope) {
        $scope.CustomStyle = {};
        $scope.BColor = "Yellow";
        $scope.Color = "Blue";

        $scope.SetStyle = function () {
            $scope.CustomStyle = {
                'background-color': $scope.BColor,
                'color' : $scope.Color
            };
        }
    });
</script>

<div ng-app="app" ng-controller="StyleController">
    Select background:
    <select ng-model="BColor" ng-change="SetStyle()">
        <option>Red</option>
        <option>Green</option>
        <option>Blue</option>
        <option>Yellow</option>
    </select>
    Select text color:
    <select ng-model="Color">
        <option>Red</option>
        <option>Green</option>
        <option>Blue</option>
        <option>Yellow</option>
    </select>
    <button ng-click="SetStyle()">Set</button>
    <hr />
    <span ng-style="CustomStyle">TechFunda.com</span>
</div>

In the HTML block, two drop downs for Background and text color values respectively. Both have their own ng-model set that is defined in the controller. Additionally, onchange of the background drop down we are calling SetStyle function so that as soon as user changes this drop down value, the element style gets updated.

The same function is also called on ng-click of the button.

In last of part of the snippet, we have used ng-style on the span to CustomStyle object defined in the controller (that is getting updated on change and on click of button).

Now as soon as user changes the drop downs values and click on the button, the span style (background and text color) is updated.

 Views: 9926 | Post Order: 57




Write for us