Broadcast Parent Event after Child listener loads in AngularJS

811 views Asked by At

I am having three controllers- Parent and Child1 and Child2. Child1 and Child2 are tabs inside parent contoller

<div ng-controller="parent">
  <!-- some HTML -->
  <div ng-controller="child1"></div>
  <div ng-controller="child2"></div>
 <!-- Keeping the code minimal for tab. Otherwise its long code -->
</div>

Parent controller is calling the service to get some data then broadcasts the event. Child listens that event, get the data and perform necessary thing.

But sometimes my child listener is not registered when parent event gets broadcasts (So listener in child will not work). Used timeout function for the same to delay the event broadcasts but it screws up on slow internet connection. Is there a way to make sure that my broadcast listen is always fired up after my child listener is registered. Below is the following code as of now

.controller('parent',function($scope,$timeout,someService,){
  someService.then(function(fetchData){
        $timeout(function () {
           $scope.$broadcast('someEvent',fetchData);
         },300);
  })
})
.controller('child1',function($scope){
//Some initializations
  $scope.$on('someEvent', function(event, fetchData) {
       //some work based on fetchData
  });
})

I am new to angularJS and not finding an appropriate solution online. Please guide. Thanks in advance :)

1

There are 1 answers

0
Isaac On

Probably the best solution is what @Vaibahv Shah said, add a $scope.$watch on the parent value from within the child controller.

Like this:

.controller('parent',function($scope,$timeout,someService,){
  someService.then(function(fetchData){
        $scope.fetchData = fetchData;
  })
})
.controller('child1',function($scope){
//Some initializations
  $scope.$watch('fetchData', function() {
       //some work based on fetchData
       console.log($scope.fetchData);
  });
})