0

必要なコントローラーへのメッセージブロードキャストを処理するために使用されるサービスがあります。

サービス:

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

コントロール:

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

4

2 に答える 2

0

$broadcast メソッドに引数を渡すことができるので、次のようにすることができます。 $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

于 2013-11-04T19:15:05.283 に答える
0

メイン ページには の 1 つのインスタンスがありAlertCtrl、モーダルが開くたびに別のインスタンスが作成されます (これを確認するには、console.log を追加します)。モデルの内部はインスタンス化され、イベントがブロードキャストされたAlertCtrlにリッスンを開始します。

于 2013-11-04T19:18:08.833 に答える