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?
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');
});
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
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With