How to share data in AngularJS
If you are a Angularjs(1.x) developer you may have used $rootScope to share data between controllers. The $rootScope shouldn’t be used to share variables when we have things like services and factories. Services provides better way to share data in Angularjs. Angularjs provides value and constant services to share data between controllers. Value and constant services could be used to store some data and access it at global level of you Angularjs app.
Value
A value is nothing more than a simple injectable value. If you want to keep some data temporarily across your app until you close the browser. For example if you want to store user name and role and some info across the application you can use value service. value service stores some data and returns it. We can store any type of data like string, number, object, array.
For example
angular.module('app', []);
.value('user', {
name:"Dinesh",
id:"1000",
role:"Admin"
});
.controller('MyController', function($scope,user) {
//here you can access user object. you can also set user object here
});Value differs from constant in that value can not be injected into configurations, but it can be intercepted by decorators.
Constant
A constant is similar to value. Difference is that you can inject constant everywhere. Where as value can not be injected into configurations. That means value of constant should never be changed.
var app = angular.module('app', []);
app.constant('PI', 3.14159265359);app.config(function(PI){
var radius = 4;
//PI can be injected here in the config block
var perimeter = 2 * PI * radius;
});
