Monday, 30 November 2015

Difference in AngularJS $rootScope and $scope;


Angularjs share the object which will work like a mediator between the View and Controller. AnjularJs share the two scope which will help to make the glue between View and controller as $scope and $rootscope.


$Scope : It is an object in AngularJs and 
use for communicating between
 the view and controller.
We can find the ng-model
 properties in particular 
controller from the particular
 page by using $scope.




$rootScope : It is work like global variable. 
An app can have only one root scope and the
 value in the root scope share by all controller.
 $scope is children scope for $rootScope. 
We can get all ng-model properties in any
 controller from any page by using this.





Code snippet :

<!doctype html>
<html>
<body ng-app="myApp">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);

        app.controller('controller1', function ($scope, $rootScope) {
            $scope.msg = 'World';
            $rootScope.name = 'AngularJS root';
        });

        app.controller('controller2', function ($scope, $rootScope) {
            $scope.msg = 'Dot Net Tricks';
            $scope.myName = $rootScope.name;
        });
    </script>
    <div ng-controller="controller1" >
        Welcome to {{msg}}!
        <br />
        Welcome to {{name}}!
    </div>
    <br />
    <div ng-controller="controller2" >
        Welcome to {{msg}}!
        <br />
        Hey {{myName}}!
        <br />
        Hi {{name}}!
    </div>
</body>

</html>

No comments:

Post a Comment