Friday 11 March 2016

$rootScope in angularjs

Hi,

$rootScope-

Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide event emission/broadcast and subscription facility. 


The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.

Example-

Please run the following sets of command-

ionic start myApp blank
cd myApp
ionic platform add android


In your index.html file add following lines of code-

<div ng-controller="MyAppController" style="border:2px solid blue; padding:5px">
 Hello {{msg}}!
 <br />
 Hello {{name}}!
 (rootScope)
</div>

In your app.js file add following lines of code-

myApp.controller('MyAppController', function ($scope, $rootScope) {
 $scope.msg = 'World';
 $rootScope.name = 'AngularJS';
 });


Note-

When you use ng-model with $rootScope objects then AngularJS updates those objects under a specific $scope of a controller but not at global level $rootScope.
Create a private $scope for each controller to bind it to the view.





Thanks...






No comments:

Post a Comment