What is $rootscope and how do we use it?

$rootscope provides access to the top of the scope hierarchy, a scope provides a separation between View and its Model. Every application has a $rootScope provided by AngularJS and every other scope is its child scope. Now see how to use it step by step, Step 1 First of all you need to add an external Angular.js file to your application, “angular.min.js.” For this you can go to the AngularJS official site or download my source code and then fetch it or you can click on this link to download it: ANGULARJS. After downloading the external file you need to add this file to the Head section of your application. 1. 2. 3. 4. Step 2 Now after adding the External JS file the first thing you need to do is to add ng-app in the Tag otherwise your application will not run. 1. Now, I will create a JavaScript function in which the $rootScope service will be initiated. 1. Here, I created two angular.modules, in the first module I created a controller named “x”, in this controller the “showAlert” variable is used with the $rootScope, in this a showAlert message is provided. In the second controller a variable “val” is used but it is taken under $scope, the value of rootScope is provided in this variable and then is provided in the alert. Now our work on the View is completed so we can work on the ViewModel. Step 3 1. 2. 3. 4. 5. 6. {{val}} 7. 8. 9. Here, I took a Div that is bound using the ng-app, after this two Divs are used, one of these is bound to the first controller, “x”, and the second is bound to “x2”; both use the ng-controller. In the second div the “val” variable is bound so this div will display the text that is passed in the val. Output On running the application an Alert Message will be displayed while the page is loading, When you click on the “OK” button the same message will be displayed on the webform as well. The complete code of this application is as follows, 1. 2. 3. 4. 5. 15. 16. 17. 18. 19. 20. 21. {{val}} 22. 23. 24. 25.

Comments