RONE
RONE

Reputation: 5485

AngularJs $emit and $broadcast and $on issue

Trying to understand the $emit and $broadcast and $on events of angularjs, Understood the theory part. but could not able to understand practical thing.

Please have a look at this, Why I am not getting the console.log message

HTMl

<div ng-app="demo">
   <div ng-controller="ParentCtrl as parent" class="ng-scope">
  {{ parent.data }}
  <div ng-controller="SiblingOneCtrl as sib1" class="ng-scope">
      {{ sib1.data }}
  </div>
</div>
</div>    

JS

var app = angular.module('demo', []);

app.controller('ParentCtrl',function($scope) {

  $scope.$broadcast('parent', 'Some data'); // going down!

});

app.controller('SiblingOneCtrl',function($scope) {

  $scope.$on('parent', function (event, data) {
    console.log(data); // 'Some data'
  });

});

Fiddle Demo

Upvotes: 2

Views: 271

Answers (1)

Cathal
Cathal

Reputation: 1790

Nothing really wrong with the code except that the broadcast is happening before the child controller has a chance to instantiate. use a timeout as per http://jsfiddle.net/hadx9zys/

setTimeout(function() {
  $scope.$broadcast(...
}, 1000);

Upvotes: 1

Related Questions