Introduction:

In this article we will explain how to ng-style directive in AngularJS or What is ng-style directive in AngularJS or why ng-style directive in AngularJS or how to change style of html element in AngularJS with example.

  • Description:

 

In AngularJS ng-style  directive use to set CSS style of a particular element. Its specifies the style attribute for the HTML element. The value of the ng-style attribute must be an object, or an expression returning an object. The object consists of CSS properties and values, in key value pairs.

Let’s see an example of ng-style in angularjs

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
 
    <script>
        var app = angular.module("app", []);
        app.controller("StyleController", function ($scope) {
            $scope.CustomStyle = {};
            $scope.BackColor = "Yellow";
            $scope.textColor = "Blue";
 
            $scope.ChangeStyle = function () {
                $scope.MyStyle = {
                    'background-color':$scope.BackColor,
                    'color': $scope.textColor,
                    "font-size": "25px",
                    "padding": "10px"
                };
            }
        });
    </script>
 
</head>
<body>
    <div ng-app="app" ng-controller="StyleController">
        Select background:
        <select ng-model="BackColor" ng-change="ChangeStyle()">
            <option>Red</option>
            <option>Green</option>
            <option>Blue</option>
            <option>Yellow</option>
        </select>
        Select text color:
        <select ng-model="textColor">
            <option>Red</option>
            <option>Green</option>
            <option>Blue</option>
            <option>Yellow</option>
        </select>
        <button ng-click="ChangeStyle()">Set</button>
        <hr />
        <span ng-style="MyStyle">Sqltutorialspoint.com</span>
    </div>
</body>
</html>

  

Output:



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

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


I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like