Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, broadcast not working

Tags:

angularjs

my aim is to send some data from an angular controller to another.

Here is the controller who has to send the datas :

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

}]);

Here is the second controller

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

        //this event is never fired

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

My view is designed that way :

 <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>
like image 219
Deblaton Jean-Philippe Avatar asked Aug 15 '13 07:08

Deblaton Jean-Philippe


2 Answers

I think you need to use $rootScope instead for $scope.$broadcast. See good example in JSFiddle

like image 73
Maxim Shoustin Avatar answered Oct 10 '22 23:10

Maxim Shoustin


Depending upon how the controllers are structured w.r.t to $broadcast message would be routed.

As per documentation

Dispatches an event name downwards to all child scopes (and their children) notifying the registered ng.$rootScope.Scope#$on listeners.

This means the controller that is sending the broadcast should be defined on the parent html of the child controller html.

Based on your html structure, use $rootScope.$broadcast. Inject the $rootScope into the MapCtrl and call $broadcast method on it.

like image 40
Chandermani Avatar answered Oct 11 '22 01:10

Chandermani