To share data between controllers it is common to use service.
I found that using $rootScope.$broadcast
is really convenient if the data I have to share is a []
or an {}
.
For me the advantage of using broadcast is that you don't have to use watcher to check if the data has been loaded into the service. Also less code to write.
So my questions are :
- Is it ok to use $broadcast
- Is there some inconvenient using $broadcast
Here is some examples using both "techniques" to show what I mean.
Example using $rootScope.$broadcast
// controller is registering 'list-loaded'
angular.module('myApp').controller(
'ControllerOne'
['$rootScope','$scope',
function ($rootScope, $scope) {
// the data
$scope.data = {
list : ["foo","bar"]
}
// sending the event with the data
$rootScope.$broadcast('list-loaded', { list: $scope.data.list });
}
]
);
//controller is listening for 'list-loaded'
angular.module('myApp').controller(
'ControllerTwo',
['$rootScope','$scope',
function ($rootScope, $scope) {
// empty data
$scope.data = {}
// when the event is received we set the data
$scope.$on('list-loaded', function(event, args) {
$scope.data.list = args.list;
});
}
]
);
Example using service
// the service
angular.module('myApp').factory(
'Service',
[
function() {
// the data to be shared
var list = []
return {
setList : function(pList){
list = pList;
},
getList : function(){
return list;
}
};
}
]
);
//controller is setting list into Service
angular.module('myApp').controller(
'ControllerOne',
['$scope', 'Service',
function ($scope, Service) {
// setting the data to service
Service.setList(["foo","bar"])
}
]
);
//controller is getting list from Service
angular.module('myApp').controller(
'ControllerTwo',
['$scope','Service',
function ($scope, Service) {
// getting the data from service
$scope.data = {
list : Service.getList()
}
}
]
);