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?
-
It is possible - look at @Alan answer - but it is not recommended. What will the var contain ?Okazari– Okazari2015-07-30 12:19:46 +00:00Commented Jul 30, 2015 at 12:19
-
4You should use Aseem's answer, leveraging the $rootScope for variables is considered a big design flaw in the angular world. Which is why services/factories exist.mikeswright49– mikeswright492015-07-30 12:28:00 +00:00Commented Jul 30, 2015 at 12:28
3 Answers
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/
Comments
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);
}]);