角度,广播不起作用

Deb*_*ppe 10 angularjs

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

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

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

}]);
Run Code Online (Sandbox Code Playgroud)

这是第二个控制器

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

        //this event is never fired

        $scope.ExcelCols = excelCols;
    });
}]);
Run Code Online (Sandbox Code Playgroud)

我的观点是这样设计的:

 <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>
Run Code Online (Sandbox Code Playgroud)

Cha*_*ani 15

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

根据文件

将事件名称向下调度到所有子范围(及其子级),通知已注册的ng.$ rootScope.Scope#$ on listeners.

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

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


Max*_*tin 6

我认为你需要使用$rootScope而不是$scope.$broadcast.在JSFiddle中查看好的示例