Understanding $scope and $rootscope in angular by relating with MVC architecture?


  • Understanding $scope and $rootscope in angular by relating with MVC architecture?

    • December 12, 2016
    • By Riddhi Kadiya

    This is very basic concept of angular js and any newbie who starting on Angularjs development comes with this question. On the web, I found many articles on this but thought it will be easy if I will explain it by relating to MVC architecture, because of most of the developers worked on this model already so for them easy to understand.

    If you are new to MVC then please read this article https://www.tutorialspoint.com/struts_2/basic_mvc_architecture.htm

    Angularjs also follow MVC pattern. In AngularJs $rootScope works like component used in the controller in MVC and as you know component can be used in any controller. In the same way, $rootScope is available in all angular controllers. You can use $rootScope in any controller by injecting it.

    In AngularJs $scope works like individual controller in MVC and it’s available per controller. You can not use $scope value in another controller and for that, you need to use $rootScope.

    $rootScope is created with ng-app whereas $scope is created with ng-controller.

    In angularJs, there may be multiple $scope exists, but exactly one $rootScope is available. We can say that $rootScope is global whereas $scope is local.

    If we want to use the $rootScope , How can we use it?

    $rootScope is the first scope created in the application. It is available when angular run () method executed.

    Example:

    var app = angular.module('myApp',[ ]);
    app.run(function($rootScope){
    $rootScope.Math = Math;
    });

    We have assigned the Math object into the $rootScope. These will give access to all the JavaScript Math functions like min () and max () in the whole application.

    If we want to use the $scope , How can we use it?

    The $scope is created in the application controller.

    Example:

    var app = angular.module('myApp',[ ]);
    app.controller('mainController', [‘$scope’, function($scope){
    $scope.Math = Math;
    }]);

    We have assigned Math object into the $scope. These will give access to all the JavaScript Math functions like min () and max () in the main view which implements “mainController”.

    • 522

Let's Talk