2013-11-04 2 views
0

필요로하는 컨트롤러에 메시지 브로드 캐스팅을 처리하는 데 사용되는 서비스가 있습니다.Angular JS는 모달 창을 포함하여 여러보기에 메시지를 전송합니다.

서비스 :

.factory('mySharedService', function($rootScope) { 
    var sharedService = {}; 

    sharedService.message = ''; 

    sharedService.prepForBroadcast = function(msg) { 
    this.message = msg; 
    this.broadcastItem(); 
    }; 

    sharedService.broadcastItem = function() { 
    $rootScope.$broadcast('handleBroadcast'); 
    }; 
    return sharedService; 
}); 

CNTL :

function AlertCtrl($scope, mySharedService) { 
    $scope.msgs = []; 
    $scope.$on('handleBroadcast', function() { 
    $scope.msgs.push(mySharedService.message); 
    }); 
    $scope.closeAlert = function(index) { 
    $scope.msgs.splice(index, 1); 
    }; 
} 

HTML : 그것은 예상대로

<div ng-controller="AlertCtrl"> 
    <alert ng-repeat="msg in msgs" type="msg.type" close="closeAlert($index)">{{msg.msg}}</alert> 
</div> 

그래서 나는 HTML 메시지를 조각을 드롭하고있는 모든이 표시된다

경우를 제외하고 모달 창에서.

제 질문은 : 방송 메시지를 모달 창에 표시하려면 어떻게합니까? 여기

는 plnkr입니다 : http://plnkr.co/edit/l6ohBYRBMftpfxiKXvLr?p=preview

답변

0

의 인스턴스가 하나 있습니다. 메인 페이지에이 있고 모달이 열릴 때마다 다른 인스턴스가 생성됩니다 (이를 확인하기 위해 console.log를 추가하십시오). 모델 내부의 AlertCtrl이 인스턴스화되어 이벤트가 브로드 캐스팅 된 후 의 수신 대기를 시작합니다.

+0

hmmmmmm, 그래서 메시지가 방송 된 후에 모달이 터지면 모달에 메시지 세트가 생깁니 까? – user2762149

+0

ModalDemoCtrl에 msgs 목록을 넣고 (항목과 마찬가지로) 모달에 전달하십시오. 새 메시지가 목록 (예 : 비동기 작업)에 푸시 될 때마다 모달 메시지가 열려 있으면 해당 메시지가 모달로 표시됩니다 (그렇지 않으면 존재하지 않을 수도 있음). –

0

당신은 $ 방송 메소드에 인수를 전달할 수 있습니다, 그래서 당신은 할 수 : $rootScope.$broadcast('handleBroadcast', 'your message here');

을하고 청취자에 :

$scope.$on('handleBroadcast', function(ev, arg){ 
    $scope.msgs.push(msg); 
}); 

가 보라 : http://docs.angularjs.org/api/ng $ rootScope.Scope # methods_ $ broadcast

+0

방송이 이미 작동 중입니다. 내 질문에 왜 그것이 모달에 중첩 된 경우 작동하지 않습니다 무엇입니까? – user2762149

관련 문제