2013-03-29 8 views
1

외부 구성 요소에 대한 구성 개체를 만드는 서비스가 있습니다. config 속성 중 하나는 선택적 이벤트로, 일부 이벤트 (비 각도)가 트리거되면 호출됩니다.angularjs 서비스에서 메시지 보내기

{ 이벤트 핸들러 : 기능 (전자) {...} } 나는 현재 컨트롤러에 메시지를 보내려면이 이벤트 핸들러 내부

. $ 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"); 
      } 
    } 
    } 
    }]); 
관련 문제