2

I have a service which creates a configuration object for an external component. One of the config properties is an optional function that gets called when some event (non angular) gets triggered.

e.g. { eventHandler:function(e) { ... } }

Inside this eventhandler I want to send a message to the current controller. I tried getting instance of $rootService but it doesn't know about $broadCast.

update : the code (simplified version, to keep code short)

app.service('componentService',['$rootScope', 
  function($rootScope) {
     this.getConfig = function() {
         return {
            transition:true,
            ... // other config parameters
            clickHandler:function(e) { // event called by external library, e = event args 
               $rootScope.$broadCast("myEvent",e.value);
            };
     };
     return {
        getConfig : this.getConfig
     }
   }]); 
4

1 回答 1

5

http://plnkr.co/edit/BK4Vjk?p=preview

Check out the example I made above. It should work.

There's a few syntax errors in your snippet of code. I wasn't sure if it was because you were just quickly typing it or if they're really there.

Basically:

app.controller('MainCtrl', function($scope, componentService) {
  var config = componentService.getConfig();
  $('#nonAngular').bind('click', config.clickHandler);
  $scope.$on('myEvent', function(e, value) {
    console.log('This is the angular event ', e);
    console.log('This is the value ', value)
  });
});

app.service('componentService',['$rootScope', 
  function($rootScope) {
     this.getConfig = function() {
         return {
            transition:true,
            clickHandler:function(e) { // event called by external library, e = event args 
               $rootScope.$broadcast("myEvent", "Some value you're passing to the event broadcast");
            }
     }
   } 
  }]); 
于 2013-03-29T22:50:53.467 回答