Mawg
Mawg

Reputation: 40140

Syntax: how to listen or an $emit in a Service?

I want to listen for 'myEmittedEvent' on rootScope, but have a problem with this code:

app.service('MyService',function($rootScope){     
      $rootScope.$on('myEmittedEvent', function(){    <===== error here
           // code goes here
      });
});

The Browser console shows Uncaught SyntaxError: Unexpected token . and the Brackets IDE says Expected ':' and instead saw '.' - W116

What am I doing wrong?

Update

The $rootScope.$on code is fine in a controller. Even in my service - but only before the return part. I expect that it should be in the object which the service instantiates.

I am an Angular beginner, how do I $on or $watch in a service?

Upvotes: 0

Views: 205

Answers (1)

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

please try

app.service('MyService',['$rootScope',function($rootScope){     
  $rootScope.$on('myEmittedEvent', function(){    <===== error here
       // code goes here
  });

  return {};

}]);

Upvotes: 1

Related Questions