Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$broadcast and $on is not working on template which is based on ng-if

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

like image 262
cuongle Avatar asked Dec 20 '22 01:12

cuongle


2 Answers

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

$timeout(function() { $scope.$broadcast("showEvent"); },0);
like image 174
Chandermani Avatar answered May 05 '23 04:05

Chandermani


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.

like image 24
Christoph Avatar answered May 05 '23 04:05

Christoph