1

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?

Manolis
  • 893
  • 1
  • 14
  • 33
user168983
  • 822
  • 2
  • 10
  • 27

2 Answers2

6

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

JulCh
  • 2,710
  • 2
  • 19
  • 21
  • As I said here "myObject" is an array returned froma api response, can I use it in my child scope and assign it to someother array there? – user168983 Nov 25 '16 at 20:14
  • Yes, you can. I've made a little codepen with a simple api call and response display based on $broadcast/$on : http://codepen.io/anon/pen/ENvjVY – JulCh Nov 25 '16 at 23:33
1

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.

Pedro Vaz
  • 820
  • 5
  • 11
  • 1
    It's actually more likely that you'll have `$scope.$on..` instead of `$rootScope.$on...`. Also, your object will be the second parameter of your callback, the first one is an event object – Robin-Hoodie Nov 25 '16 at 14:59