angularjs广播从未收到过

时间:2015-04-29 18:17:19

标签: angularjs angularjs-scope angular-broadcast

我有两个注射器,一个范围的事件永远不会到达另一个范围,即使它们是相同的范围...

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);
}]);

更新

我的主要目标是了解Google地图何时加载并初始化...

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'...

一切正常,直到"about to init"永远不会登录到控制台并且api没有设置

0 个答案:

没有答案