I got problem to broadcast event from parent scope to child scope which I think the root core might be child controller is not initialized.
Assume I have html
:
<div ng-controller="ParentController">
<button type="button" ng-click="show()">Show Template</button>
<div ng-if="showTemplate">
<div ng-include="'template.html'" ng-controller="ChildController"></div>
</div>
</div>
and controllers:
var myApp = angular.module("myApp", []);
myApp.controller('ParentController', ['$scope', function ($scope) {
$scope.show = function(){
$scope.showTemplate = true;
$scope.$broadcast("showEvent", 1);
};
}]);
myApp.controller('ChildController', ['$scope', function ($scope) {
$scope.$on("showEvent", function(event, id){
alert(id);
});
}]);
When the button Show Template
is clicked, the flag showTemplate
is set to show the template, also an event showEvent
is broadcast-ed to child scope.
But the scope in ChildController
cannot catch this event since the child controller might initialize later.
Is there any way to work around this?
The code in here: http://plnkr.co/edit/HV6aco
Wrap the call of broadcast into a $timeout
and you are good to go i believe
$timeout(function() { $scope.$broadcast("showEvent"); },0);
Since you are using ng-if
the DOM nodes with the ChildController
are just not present at the time when the event is fired.
I see two possibilities:
Move the ChildController
somewhere above the ng-if
use ng-show
instead of ng-if
See the updated plunkr: http://plnkr.co/edit/NluFBJ
However, if you are really only interested in getting notified when the template is being created, then I would suggest to just go for @Roy Daniels solutions and just don't use $broadcast
/$on
at all and instead put the code you wanted to run directly into the ChildController
since that will be executed anyway each time the template is being created.
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