latest Post

What is “$rootScope” in AngularJS?

A scope provides a separation between View and its Model. Every application has a $rootScope provided by AngularJS and every other scope is its child scope.

Using $Rootscope

Using rootscope we can set the value in one controller and read it from the other controller.

The following is the sample code snippet,

code

    <!DOCTYPE html>
    <html ng-app="myApp">
   
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
        </script>
        <script>
            var myApp = angular.module('myApp', []);
   
            function controllerOne($scope, $rootScope)
            {
                $rootScope.name = 'From Rootscope set in controllerOne';
            }
   
            function controllerTwo($scope, $rootScope)
            {
                $scope.name2 = $rootScope.name;
            }
        </script>
    </head>
   
    <body>
        <div style="border: 5px solid gray; width: 300px;">
            <div ng-controller="controllerOne">
                Setting the rootscope in controllerOne
            </div>
            <div ng-controller="controllerTwo">
                Hello, {{name2}}!
            </div>
            <br />
        </div>
    </body>
   
    </html> 

About Mallikarjun A

Mallikarjun A
Recommended Posts × +

0 comments:

Post a Comment