18

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?

2
  • It is possible - look at @Alan answer - but it is not recommended. What will the var contain ? Commented Jul 30, 2015 at 12:19
  • 4
    You 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. Commented Jul 30, 2015 at 12:28

3 Answers 3

31

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/

Sign up to request clarification or add additional context in comments.

Comments

10

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);
}]);

1 Comment

Matthew is exactly right. If failed to define value as an Object, the changing value inside a particular controller doesn't get prolonged outside.
3

You could set that variable on $rootScope. and inject $rootScope into the controllers which will use the global.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.