AngularJS ngstyle



  • The ng-style directive in Angularjs is used to define the CSS style attribute for the HTML element.
  • The value of the ng-style must be an object or an expression which returning an object.
  • The ng-style object contains CSS properties and values, in key value pair.
  • The ng-style directive compile at default priority level “0”.
  • The ng-style is supported by all HTML element.

Syntax for ng-style directive in AngularJS:

<element ng-style="expression"></element>

Parameter value for ng-style directive in AngularJS:

Value Description
expression An expression which returns an object whose keys are CSS name and the values are CSS values.

Sample coding for ng-style directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller=”styleCtrl”>
        <h2>ng-style Directive in AngularJs Tutorials</h2>
        <h1 ng-style=”styleObj”>Welcome To AngularJS Tutorials </h1>
        <script>
            <var app = angular.module( "myApp" , []);
            app.controller("styleCtrl", function($scope) {
                $scope.styleObj = {
                    “color” : “white”,
                    “background-color” : “orange”,
                    “font-size” : 40 px
                }
            });>
        </script>
    </body>
</html>

Code Explanation for ng-style directive in AngularJS:

Code Explanation for AngularJS ngstyle

  1. AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
  2. The AngularJS application is defined by ng-app="myApp". The application runs inside the <body> tag. It’s also used to define a <body> tag as a root element.
  3. The ng-controller=”styleCtrl“ is an AngularJS directive. It is used to define a controller name as “styleCtrl”.
  4. The ng-style=”styleObj” is used to specify the CSS style attribute for the <h1> HTML element.
  5. The angular.module function is used to create a Module.
  6. Here we have declared a controller styleCtrl module using apps.controller() function. The value of the controller modules is stored in scope object. In AngularJS, $scope is passed as first argument to apps.controller during its constructor definition.
  7. $scope.styleObj={ “color”: “white”, “background-color”: ”orange”, “font-size” : “40px”}. Here we have declared an CSS object as “styleObj” and set the CSS name and their value.

Sample Output for ng-style directive in AngularJS:

Sample Output for AngularJS ngstyle

  1. The output displays that <h1> content as “Welcome to AngularJS Tutorials”. And the content is displayed with font color as white, background color as orange and font size as 40 pixels by using the ng-style directive in <h1> element.


Related Searches to angularjs ngstyle directive