Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $broadcast not working.

I am trying to share informations between two controllers with $scope.$on and $scope.$broadcast.

Here is the view:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
        {{content}}
    </div>
</div>

and the controllers:

.controller('ParentCtrl', ['$scope', function($scope) { 
    $scope.$broadcast('someEvent', 'bidule');
}])

.controller('ChildCtrl', ['$scope', function($scope) { 
    $scope.$on('someEvent', function(event, b) {
        $scope.content = b;
    });
}])

and the plunker

What am I doing wrong here?

like image 808
François Romain Avatar asked Feb 27 '14 16:02

François Romain


3 Answers

The child controller isn't instantiated yet. Wrapping the broadcast in a timeout works: http://plnkr.co/edit/MF7P16K1OTv46JNgkkih?p=preview

$timeout(function(){
   $scope.$broadcast('someEvent', 'bidule');
});
like image 108
kamilkp Avatar answered Oct 13 '22 10:10

kamilkp


Child not initiated. Faced the same issue and this was my solution.

.controller('ParentCtrl', ['$scope', function($scope) { 
    $scope.$on('initiateEvent', function(event, b) {
        $scope.$broadcast('someEvent', 'bidule');
    } 
}])
.controller('ChildCtrl', ['$scope', function($scope) { 
    $scope.$on('someEvent', function(event, b) {
        $scope.content = b;
    });
    $scope.$emit('initiateEvent', null); 
}])

Here i'm initiating the child and asking the parent to broadcast someEvent

like image 36
Faraj Farook Avatar answered Oct 13 '22 10:10

Faraj Farook


To broadcast an event, you simply have to call it.

The following code works perfectly :

Your view :

<div ng-controller="ParentCtrl" ng-click="myFunc()">
    <div ng-controller="ChildCtrl">
        {{content}}
    </div>
</div>

and your controllers :

.controller('ParentCtrl', ['$scope', function($scope) {
    $scope.myFunc = function() { 
        $scope.$broadcast('someEvent', 'bidule');
    }
}])

.controller('ChildCtrl', ['$scope', function($scope) { 
    $scope.$on('someEvent', function(event, b) {
        $scope.content = b;
    });
}])

Hope it helps !

like image 3
Charlesthk Avatar answered Oct 13 '22 09:10

Charlesthk