There are two ways to use global variables:
1.$rootscope
2.service
1- We can use rootscope which is the parent of all scopes. Values exposed there will be used in all controllers and templates. We can use this in a simple way by just injecting it into your controller.
Here is an example code:-
var app = angular.module('myApp', []);
app.controller('Ctrl1', function ($scope, $rootScope) {
$scope.msg = 'World';
$rootScope.name = 'AngularJS';
});
app.controller('Ctrl2', function ($scope, $rootScope) {
$scope.msg = ' Tricks';
$scope.myName = $rootScope.name;
});
<body ng-app="myApp">
<div ng-controller="Ctrl1" >
Hello {{msg}}!
<br />
Hello {{name}}!
(rootScope)
</div>
<br />
<div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
Hello {{msg}}!
<br />
Hi {{name}}! (rootScope)
</div>
</body>
This will give output: Hello world!
Hello AngularJs!
Hello tricks!
Hello AngularJs!
2- Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global'.
Here is an example code:
var myApp = angular.module('myApp',[]);
myApp.factory('EgService', function() {
return {
name : 'Example'
};
});
function MyCtrl($scope, EgService) {
$scope.name = EgService.name;
}
This is how we can use global variables in AngularJs.
0 Comment(s)