angularjs从服务发送消息

时间:2013-03-29 19:29:54

标签: angularjs

我有一个为外部组件创建配置对象的服务。 其中一个配置属性是一个可选函数,当某个事件(非角度)被触发时会被调用。

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

在这个事件处理程序中,我想向当前控制器发送一条消息。 我尝试获取$ rootService的实例,但它不知道$ broadCast。

更新:代码(简化版,保持代码简短)

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
     }
   }]); 

1 个答案:

答案 0 :(得分:4)

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

查看我上面的例子。它应该工作。

您的代码段中存在一些语法错误。我不确定是不是因为你只是快速输入它或者它们真的在那里。

基本上:

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");
            }
     }
   } 
  }]); 
相关问题