1

Please refer - http://jsfiddle.net/U3pVM/18701/

In the console, I only see "outer1" being logged, the inner scope does not log. Is something missing?

var app = angular.module("myapp", []);

app.controller("outer1", function($scope) {
$scope.$on("newmessage", function() {
        console.log("outer1");
});
$scope.$broadcast("newmessage");
});
anand patil
  • 507
  • 1
  • 9
  • 26

1 Answers1

1

It's a timing issue - the children are initialized after the parent had already fired $broadcast. If you delay $broadcast using $timeout, the children will receive the event (update fiddle):

app.controller("outer1", function($scope, $timeout) {
    $scope.$on("newmessage", function() {
            console.log("outer1");
    });
    $timeout(function() { // delay $broadcast using $timeout
        $scope.$broadcast("newmessage");
    }, 0);
});
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • @Oro Drori - Cool, thanks! Other than using an arbitrary timeout/interval, can we do a broadcast after children have been initialised. – anand patil Sep 17 '15 at 20:46
  • And any special reason why the timeout is "0", that's the first time i saw. can you pls explain. – anand patil Sep 17 '15 at 20:47
  • Just beginner at Angular, so curious to know. anyway, the reason i asked a solution w/o timeout is because we don't use timeout for Ajax calls, we use defer/promise. something like that would be more efficient right? – anand patil Sep 17 '15 at 20:48
  • 1
    timeout width 0 or undefined moves the callback to the end of the javascript command queue, without add additional time delay. It means that it will happen sometime in the future, when the queue gets to it - [detailed explanation](http://stackoverflow.com/a/779785/5157454) – Ori Drori Sep 17 '15 at 20:50
  • 1
    More efficient would be not to use child controllers at all. Use nested directives, pass data using attributes, and your life would be easier :) – Ori Drori Sep 17 '15 at 20:51