I want a variable that can be used in all the controllers but don't want to create a service for it .Is it possible in angular js?
We always need to declare global variable file for our angular 8 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
You can make use of constants or values.
Constants
var app = angular.module('myApp', []);
app.constant('appName', 'Application Name');
app.controller('TestCtrl', ['appName', function TestCtrl(appName) {
console.log(appName);
}]);
Values
var app = angular.module('myApp', []);
app.value('usersOnline', 0);
app.controller('TestCtrl', ['usersOnline', function TestCtrl(usersOnline) {
console.log(usersOnline);
usersOnline = 15;
console.log(usersOnline);
}]);
http://ilikekillnerds.com/2014/11/constants-values-global-variables-in-angularjs-the-right-way/
Use value()
to define an object, and store your 'global variables' as properties of that object. Then add the object as a dependency to any controller that needs to access its properties. This has a positive side-effect of encapsulating all your variables into a single object, which is tidy and less-likely to suffer namespace collision.
Here's the pattern:
app.value('myVars', {
usersOnline:0
});
app.controller('TestCtrl', ['myVars', function TestCtrl(myVars) {
console.log(myVars.usersOnline);
myVars.usersOnline = 15;
console.log(myVars.usersOnline);
}]);
FYI Aseem's answer won't work, because his example uses value()
with a primitive type. To be clear about what doesn't work:
app.value('usersOnline', 0);
app.controller('TestCtrl', ['usersOnline', function TestCtrl(usersOnline) {
console.log(usersOnline);
usersOnline = 15; // <-- THIS WILL NOT PERSIST outside the controller.
console.log(usersOnline);
}]);
You could set that variable on $rootScope. and inject $rootScope into the controllers which will use the global.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With