Difference between $scope and $rootScope in angularJS


The main difference is the availability of the property assigned with the object.

$rootScope

  $scope $rootScope
1. It provides local access It provides global access
2. We can have many $scope s We can have only one $rootScope
3. Cannot be used outside the controller Can be used in any controller
4. $scope is created with ng-controller $rootscope is created with ng-app
5. $scope is child object of $rootScope $rootScope is root object

 

Difference between scope and rootscope

$rootScope and $scope Example

<script src="~/Scripts/angular.min.js"></script>

<div ng-app="MyApp">
    <div class="show-scope-demo">
        <div ng-controller="GreetController">
            Hello {{name}}!
        </div>
        <div ng-controller="ListController">
            <ol>
                <li ng-repeat="name in names">{{name}} from {{department}}</li>
            </ol>
        </div>
    </div>
</div>

<script>
    angular.module('MyApp', [])
  .controller('GreetController', ['$scope', '$rootScope',
    function ($scope, $rootScope) {
        $scope.name = 'World';
        $rootScope.department = 'Angular';
    }
  ])
  .controller('ListController', ['$scope',
    function ($scope) {
        $scope.names = ['venki', 'rohit', 'ganesh'];
    }
  ]);
</script>

Output:

Hello World!

  1. venki from Angular
  2. rohit from Angular
  3. ganesh from Angular

 

Happy coding….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s