AngularJS从$ rootScope广播到模态窗口范围

时间:2014-07-24 08:48:30

标签: angularjs

有没有办法从$ rootScope广播到模态窗口$ scope?

我的$ rootScope是ApplicationController,我正在那里收听socket.io事件。当我处理这个事件时,我想$ $广播到ChatController(模态窗口)$ scope(可能已经打开,所以解决方案对我不会有帮助)。

演示此问题的简单示例:

的index.html:

    <!DOCTYPE html>
<html ng-app="App">

  <head>
    <link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <script data-require="angular.js@1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script data-require="bootstrap@3.1.1" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script data-require="angular-ui-bootstrap@0.11.0" data-semver="0.11.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="ApplicationController">
    <h1>Hello Plunker!</h1>
    <input type="button" value="open modal" ng-click="openModal()">
    <div ng-controller="NotModalController">
      {{fields.field1}}
    </div>
  </body>

</html>

的script.js:

(function() {
  var app = angular.module("App", ["ui.bootstrap"]);

  app.controller("ApplicationController", function($scope, $modal) {
    $scope.openModal = function() {
      var modalInstance = $modal.open({
        templateUrl: 'chat.html',
        controller: 'ModalController',
        size: 'lg',
        resolve: {

        }
      });

      modalInstance.result.then(function() {
        console.log('modal closed');
      }, function() {
        console.log('modal dismissed');
      });

      setTimeout(function() {
        console.log('broadcasting event');
        $scope.$broadcast('someEvent', 'broadcasted value');
      }, 3000);
    };
  });

  app.controller("NotModalController", function($scope) {
    $scope.fields = {
      field1: 'initial'
    };
    $scope.$on('someEvent', function(event, args) {
      $scope.fields.field1 = args;
    });
  });

  app.controller("ModalController", function($scope) {
    $scope.fields = {
      field1: 'initial'
    };
    $scope.$on('someEvent', function(event, args) {
      $scope.fields.field1 = args;
    });
  });

})();

modalTemplate.html

<div>
  {{fields.field1}}
</div>

plunkr网址:http://plnkr.co/edit/9xpwmleZJnAG66cGWcYO

1 个答案:

答案 0 :(得分:0)

认为你应该使用$ rootScope。$ broadcast而不是$ scope。$ broadcast