Monday, July 6, 2015

$rootScope service in AngularJS

$rootScope is the global scope which acts as the parent for all the controllers $scope, values set in one controller’s $scope can be accessed in other controllers $scope across the application.

The following example defines 2 controllers, the 1st controller sets value for the variable rootValue and the 2nd controller accesses the value from the rootScope and displays it in the view.

Controller Scripts
var app = angular.module("myApp", [])
app.controller("rootScopeController1", function($scope, $rootScope) {
    $rootScope.rootValue = "Value from rootScopeController1";

app.controller("rootScopeController2", function($scope, $rootScope) {
    $scope.globalValue = $rootScope.rootValue;

<html ng-app="myApp">
    <meta charset="utf-8">
    <title>AngularJS - Basic</title>
<div ng-controller="rootScopeController1" style="color:red">

<div ng-controller="rootScopeController2" style="color:green;">
    <script src="angular.min.js"></script>
          <script src="rootScope.js"></script>

Search Flipkart Products:

No comments: