Saturday, August 26, 2017

$rootScope in angularjs

  • $rootScope is the parent scope object and it will be single for entire application.
  • The data and methods of $rootScope object will be available to all the controllers.
  • All $scope objects are child objects of $rootScope.
  • The ng-app directive initializes the application.
Example: 
JS :
var MyApp = angular.module("MyApp",[]);
MyApp.controller('DemoRootScope', function ($rootScope) {
    $rootScope.rootScopeName = "Root scope value";
});

MyApp.controller('DemoChildScope', function ($scope,$rootScope) {
    $scope.Name = "scope value";
});

HTML :
    <span class="bi">Sibling Controller1 :</span><br/>
    <div ng-controller="DemoRootScope">
        <span class="b"> Root Scope Name:</span> {{rootScopeName}}
    </div>
    <br/>
    <span class="bi">Sibling Controller2 :</span><br/>
    <div ng-controller="DemoChildScope">
        <span class="b">  Child Scope Name:</span> {{Name}} <br/>
        <span class="b">  Root Scope Name: </span> {{rootScopeName}}
    </div>

No comments:

Post a Comment