2013-03-29 98 views
1

我有一個服務爲外部組件創建一個配置對象。 其中一個配置屬性是一個可選函數,當某個事件(非角度)被觸發時被調用。angularjs從服務發送消息

例如 { 事件處理程序:功能(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

請出示你的一些服務代碼(例如,它注入$ rootScope?),你的事件處理程序代碼。 –

回答

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