Menu ▼

ng-style directive in AngularJS

The ng-style directive allows you to set CSS style on HTML element using expression.

<p ng-style="customestyle">text</p>

In this example we will apply customstyle expression to paragraph using ng-style. and when user select any of the checkbox, ng-change fires the checkbox change event and update the customstyle based on the selection.

Select the above option to change this paragraph styles.

Source code:
<html xmlns="">
    <script src=""></script>
    <div ng-app="SampleApp" ng-controller="SampleCntrl">
        <input id="chbbg" type="checkbox" ng-model="bgcolor" ng-change="setstyle();" /><label
            for="chbbg">Set background color green</label>
        <br />
        <input id="chbcolor" type="checkbox" ng-model="fontcolor" ng-change="setstyle();" /><label
            for="chbcolor">Set color white</label>
        <br />
        <input id="chbfontwt" type="checkbox" ng-model="fontbold" ng-change="setstyle();" /><label
            for="chbfontwt">Set font weight bold</label>
        <br />
        <input id="chbpad" type="checkbox" ng-model="padding" ng-change="setstyle();" /><label
            for="chbpad">Set Padding</label>
        <br />
        <p ng-style="customestyle">
            Select the above option to change this paragraph styles.</p>
        var myapp = angular.module("SampleApp", []);
        myapp.controller("SampleCntrl", function ($scope) {
            $scope.bgcolor = true;
            $scope.fontcolor = true;
            $scope.fontbold = true;
            $scope.padding = true;
            $scope.setstyle = function () {
                $scope.customestyle = {
                    "background-color": $scope.bgcolor ? "green" : "",
                    "color": $scope.fontcolor ? "#fff" : "",
                    "font-weight": $scope.fontbold ? "bold" : "",
                    "padding": $scope.padding ? "10px" : ""