@gmarziou is right, you’d better define a service in this case to share data to anywhere you want. It will be something like this:
var app = angular.module('YOUR_APP_NAME', []);
app.service('ShareService', ShareService);
function ShareService() {
// Private variable
var data = {};
// The object which will be expose as service api
var service = {};
service.getName = getName;
service.setName = setName;
return service;
// Define service methods
function getName() {
return data.name || '';
}
function setName(name) {
data.name = name;
}
}
// And then you can use it in other controllers, directives or services, just inject it
app.controller('TestController', function ($scope, ShareService) {
// Do something...
$scope.name = ShareService.getName();
$scope.setName = ShareService.setName;
});
app.directive('test', function (ShareService) {
return {
restrict: 'E',
template: '<span>{{ name }}</span>',
link: postLink
};
function postLink(scope) {
scope.name = ShareService.getName();
}
});
// ...
The best way for your use case is to use Services. Yes you can use $rootScope, and I do use rootScope sometimes, but 90% of the time using a Service will be better, it doesn’t take long to learn.
I’ve got a video that explains this, if you want to skip the parts on dependancy injects the important stuff is from 4 mins in (the video is only 5 mins).