Reputation: 844
I am working with an app where I have the following line at the end of a service in service.js.
$rootScope.$broadcast('rootScope:Object')
Here Object is the output of an API service. If I now want to use this Object in my actual app.js file, how could I use it? What does the above line specify and how to use it in later pages?
Any help is appreciated.
EDIT:
From the given answers tried the following:
In service page:
this.getobject=function(){
//http api Function call with result as response.data = resp
$rootScope.$broadcast('rootScope:resp',resp);
}
In the child scope page:
resp=[];
$rootScope.$on('rootScope:resp',function(resp) {
$scope.resp=resp;
console.log(resp);
});
$scope.$on('rootScope:resp', function(e, params){
console.log(params); // respobject
});
Unfortunately both didn't print anything on console. Any issue with the approach?
Upvotes: 1
Views: 1695
Reputation: 2878
This line means that the $rootScope (the highest scope level) will broadcast an event named 'rootScope:Object' to all the children (your app's scopes).
According to https://docs.angularjs.org/api/ng/type/$rootScope.Scope, you can add parameters to the $broadcast()
function to, in your case, pass your Object.
You will have:
$rootScope.$broadcast('rootScope:Object', myObject)
In your child scope, you can easily retrieve this with:
$scope.$on('rootScope:Object', function(e, params){
console.log(params); // myObject
});
Hope it helps.
EDIT: Here's a codepen showing loading and displaying data from an API using $broadcast/$on
Upvotes: 6
Reputation: 820
Not sure I understood your question but broadcast does nothing more than dispatch an event downwards to all child scopes.
So, in your service you probably want to have something like:
$rootScope.$broadcast('myEventNameHere', actualJavascriptObjectHere);
And on the place that you want to listen to this event, you will have something like this:
$scope.$on('myEventNameHere', function(actualJavascriptObjectHere) {
console.log(actualJavascriptObjectHere);
});
Hope that helps.
Upvotes: 1