10

我的目标是将一些数据从一个角度控制器发送到另一个。

这是必须发送数据的控制器:

myApp.controller('MapCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.loadData = function () {
        $http.get('/map/GetListDB').success(function (data, status, headers, config) {

            //Logic here is working fine, it creates a table named "ExcelCols" which is a table of strings

            $scope.$broadcast("SET_EXCEL_TITLES", $scope.ExcelCols);
        })
    }

}]);

这是第二个控制器

myApp.controller('ExcelViewCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.$on("SET_EXCEL_TITLES", function (event, excelCols) {

        //this event is never fired

        $scope.ExcelCols = excelCols;
    });
}]);

我的观点是这样设计的:

 <body ng-app="myApp">
    <div ng-controller="MapCtrl">
         //everything OK here
    </div>

    <div ng-controller="ExcelViewCtrl">
      <table>
        <thead>
            <tr>
                <th ng-repeat="col in ExcelCols">{{col}}</th>
            </tr>
        </thead>
       </table>          
    </div>

 </body>
4

4 回答 4

15

根据控制器的结构,$broadcast消息将被路由。

根据文档

向下调度事件名称到所有子作用域(及其子作用域),通知已注册的 ng.$ro​​otScope.Scope#$on 侦听器。

这意味着发送广播的控制器应该在子控制器 html 的父 html 上定义。

根据您的 html 结构,使用$rootScope.$broadcast. $rootScope在其上注入MapCtrl并调用$broadcast方法。

于 2013-08-15T07:06:55.240 回答
7

我认为您需要$rootScope改用 for $scope.$broadcast。查看JSFiddle中的好例子

于 2013-08-15T07:18:03.573 回答
3

下面是 AngularJS 的示例——控制器之间的通信:

使用共享服务进行通信的示例。

http://jsfiddle.net/simpulton/XqDxG/

"ControllerZero" Broadcast to "ControllerOne" and "ControllerTwo"

和视频教程

http://onehungrymind.com/angularjs-communicating-between-controllers/

于 2013-08-15T07:21:20.720 回答
0

另一种选择是使用 $rootScope 列出事件并使用本地 $scope 来发出它。我创建了这个 plnkr 来测试它http://plnkr.co/edit/LJECQZ?p=info

var app = angular.module('plunker', []);

app.controller('Ctl1', function($scope, $rootScope) {
  $scope.name = 'World';
  $rootScope.$on('changeValueInCtl1', function(event, value) {
    $scope.name = 'New Value from Ctl2 is: ' + value;
  });
});

app.controller('Ctl2', function($scope) {
  $scope.changeValue = function() {
    $scope.$emit('changeValueInCtl1', 'Control 2 value');
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body>
  <div ng-controller="Ctl1">
    <p>Hello {{name}}!</p>
  </div>


  <div ng-controller="Ctl2">
    <button ng-click="changeValue()">Change Value</button>
  </div>

</body>

</html>

唯一的缺点是 $rootScope 将被监听,并且必须显式调用 $destroy 。

于 2017-03-30T01:18:24.003 回答