Search code examples
angularjsangularjs-scope

Does the scope change when we change to other page?


I have created a variable with $scope in my controller. Apparently, that $scope will be applied (available) to that controller only. Can we use that $scope in other controllers of the other pages?


Solution

  • Each controller will have their own $scope. Even though there's a $rootScope that all the controllers of the page will have access, this is not the recommended approach since it's like a global variable container for the app module. The preferred way would be to use custom services.

    Using $rootScope:

    $rootScope.value = "shared value using $rootScope";
    

    This can be accessed in any views or controllers as $root.value and $rootScope.value respectively.

    Using Custom Service:

    $scope.shareCustom = function() {
      CustomService.value = "shared value using CustomService";
    };
    

    This can be accessed in any controller injecting CustomService and attaching it to its $scope.

    Snippets :

    .controller('AnyCtrl', function ($scope, CustomService) {
      $scope.customService = CustomService;
    });
    
    <p>{{customService.value}}</p>
    

    I have made Plunker Demo to illustrate both of these ways of sharing data.