- AngularJS application module can be defined using ngApp directive.
- The element where the ngApp directive used is also known as root element.This element can be accessed using $rootElement object provided by AngularJS.
- In this Demo, "We will see an example of using $rootElement to change the background color of the body element".
- Below code shows the use of the $rootElement. We have created a custom directive which has a button to be clicked.The callback function attached to this button is going to access the $rootElement which in this example is the BODY element and change its background color to green.
<!DOCTYPE html> <html lang="en"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script> <meta charset="UTF-8"> <title> AngularJS $rootElement Example </title> </head> <body ng-app="myApp"> <my-directive></my-directive> <script> var myApp = angular.module("myApp", []); myApp.directive("myDirective", ['$rootElement', "$log", function($rootElement, $log) { return { restrict: "E", template: "<button ng-click='changeGreenBackground()'>Change BackGround {{color}}</button>", link: function(scope, element, attr) { scope.changeGreenBackground = function() { $log.log($rootElement); $rootElement.css("background", "#00ff00"); }; } }; } ]); </script> </body> </html>
- Output of the above example is embedded in below JSBIN link.