4
votes

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

3

3 Answers

4
votes

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:

  1. Move the ChildController somewhere above the ng-if

  2. 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.

6
votes

Wrap the call of broadcast into a $timeout and you are good to go i believe

$timeout(function() { $scope.$broadcast("showEvent"); },0);
1
votes

You don't need to use $broadcast/$on here. Every time you show your template the code in ChildController will be initialized and run.

Take a look at this Plunker: http://plnkr.co/edit/liON6k?p=preview