Angular JS将msg广播到多个视图,包括模态窗口

Angular JS broadcast msg to multiple views including a modal window

本文关键字:视图 包括 模态 窗口 JS msg 广播 Angular      更新时间:2023-09-26

我有一个服务,用于处理向需要它的控制器广播消息。

服务:

.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

主页中有一个AlertCtrl实例,每当模式打开时都会创建另一个实例(添加控制台.log以验证这一点)。模型内的AlertCtrl被实例化,并在事件广播开始侦听。

您可以将参数传递给$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