Reputation: 653
Could anyone give me some tips on how to handle the situation when broadcast listeners aren't set before the broadcast event?
I've seen some solutions with $timeout, but they don't feel OK. Thanks!
var app = angular.module('app', []);
app.controller('ParentCtrl',
function ParentCtrl ($scope) {
this.data = 'parent';
$scope.$broadcast('parent', 'Some data'); // event is sent before any listeners are set
});
app.controller('ChildCtrl',
function SiblingOneCtrl ($scope) {
this.data = 'child';
$scope.$on('parent', function (event, data) {
document.write(data); // never activates
});
});
Working example: http://codepen.io/AndriusRimkus/pen/zqMONm
Upvotes: 4
Views: 479
Reputation: 2820
In your case, you will always try to broadcast before any listener will be subscribed.
That's because you ParentCtrl
will always initialized before ChildCtrl
.
Try to watch on you controllers like a constructors.
If you what to broadcast something to you child controllers then you need to have some events (like, clicks) to start broadcasting manually, but not from controller directly.
Upvotes: 1