angularjsangularjs-scopeangular-broadcast

angularjs broadcast never received


I have two injectors, the event from one scope never reaches the other scope even though they are the same scope supposedly...

http://jsfiddle.net/rkLzww3t/

angular.injector(['ng']).invoke(['$rootScope', function($root) {
    alert('will try to be usefull');
    $root.$on('bevent123', function() {
      alert('useful bevent123 never happens');
    });
}]);

angular.injector(['ng']).invoke(['$rootScope', function($root) {
    $root.$on('bevent123', function() {
      alert('bevent123 done from local injector, but we were not usefull');
    });
    console.log("about to $root.$broadcast('bevent123')");
    window.setTimeout(function() {
      $root.$broadcast('bevent123');
    },1000);
}]);

UPDATE

My main objective is in knowing when google maps has loaded and initialized...

var app = angular.module('module_name');

function googleCallback() {
  //run does not do anything if all modules are already loaded and initialized
  //angular.module('module_name').run(['$rootScope', function($root) {
  angular.injector(['ng']).invoke(['$rootScope', function($root) {
    console.log("about to $root.$broadcast('googleLoaded')");
    $root.googleLoaded = true;
    window.setTimeout(function() {
      $root.$broadcast('googleLoaded');
      //$root.$emit('googleLoaded');
    },1000);
  }]);
}

app.run(['$rootScope',function($root) {
  var element = document.createElement("script");
  element.type = 'text/javascript';
  element.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&callback=googleCallback";
  element.async = true;
  var domElement = document.head || document.getElementsByTagName("head")[0];
  domElement.appendChild(element);
}]);

app.controller('Controller', ['$scope','$rootScope', function ($scope, $root) {
  function initMaps() {
    console.log("initMaps()");
  }
  $scope.$on('$viewContentLoaded', function() {
    console.log('$viewContentLoaded');
    if (!$root.googleLoaded) {
      console.log("waiting for googleLoaded");
      $scope.$on("googleLoaded", function() {
        console.log("about to init");
        initMaps();
      });
    } else {
      initMaps();
    }
  });
}]);//end of app.controller('Controller'...

everything works perfect until "about to init" never gets logged to the console and the api doesn't get setup


Solution

  • The two scopes are not the same.

    I have to broadcast on $rootScope from a global function

    You can get the injector of the application via a DOM element. E.g.:

    angular.element(document.body).injector()
    

    Instead of invoke you could call get to get an angular service and use that. Definitely better then a "raw" global function.