• Understanding Angularjs scope $rootScope and $scope

    Posted on March 27, 2017 by Hamidul Islam in Angular JS.

    angular-js-scopes


    In Angularjs Scope is simply a JavaScripe object . Scope is the glue between Angularjs controller and view. The scope holds all the model data required for the view to be displayed. In Angularjs the scope is hierarchical in nature. In this article we will explain the various aspects of Angularjs scopes.


    Whats scope in Angularjs:

    Angularjs scope is JavaScripe object which holds properties and methods. This scope object is used for data binding (2 way binding)  between view (HTML) and Angular controller. So remember its just an object.

    In Angular application there can be multiple scopes. When Angular scan the DOM and encounter ng-app it creates the root scope $rootScope. Each controller will create separate child scope under the root scope. In below example it creates only root scope but no child scope. Since there are no controller defined.

    Child Scope ($scope):

    When we have controller then there would be child scope under the $rootScope. In general while writing controller we pass $scope object as an argument. This is nothing but child scope. For example

    According to the above code the imagination would be as below

     

    Note

    The $rootScope is available in the entire application.In Angularjs every application has $rootScope. The $rootScope is created when angular encounter ng-app directive. $rootScope is a parent object of all  $scope objects created in a web page. A child scope can be nested. That means a child scope can have another child scope and so on.

     

    If we have multiple controllers then the picture would be something like below

    angular-js-scopes

    Accessing $rootScope in a controller:

    We can access $rootScope from the controller. Just inject $rootScope in the controller

     

    Post Tagged with , ,

One Response so far.

  1. […] Understanding Angularjs scope $rootScope and $scope […]

Top
%d bloggers like this:

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close