【问题标题】:angularjs $boadcast and $on doesn´t work from angular.injectorangularjs $boadcast 和 $on 在 angular.injector 中不起作用
【发布时间】:2018-05-01 05:08:35
【问题描述】:

我试图在收到推送通知时将一个函数调用到控制器中,传递一个 $broadcast / 工厂,但是当通过 angular.injector 调用时广播不起作用,这里是我的代码的和平:

push.js

window.onNotification = function(data) {
        angular.injector(['ng', 'myApp']).get("laFactory").PushReceived(data.additionalData); // --> work fine
    };
         window.push = PushNotification.init({
             "android": {
                 "senderID": "123456789",
                 "icon": "system",
                 "forceShow": true
             }
         });

         window.push.on('notification', window.onNotification);

laFactory.js

.factory('laFactory', ['$http', '$rootScope', function ($http, $rootScope) {
    var laFactory = {};

    laFactory.PushReceived = function(data) {           
       $rootScope.$broadcast('handleNotify', {}); // --> don´t work when called by angular.injector!!! why not?!
    };

    $rootScope.$broadcast('handleNotify', {}); // this work fine

    return laFactory;
}

myController.js

.controller('NotificacoesController', function($scope, $rootScope, laFactory) {
    var handler = $scope.$on('handleNotify', function () {
            alert('broadcast - on');
    });

}

【问题讨论】:

  • 可能是你laFactory.PushReceived没有被调用尝试登录到laFactory.PushReceived里面的控制台看看它是否工作

标签: angularjs broadcast


【解决方案1】:

不确定它是否最好,但它有效:

angular.element(document).injector().invoke(["laFactory", function(laF) {
  laF.PushReceived({});
}]);

http://plnkr.co/edit/uVHZKxUjRErbxt2dR3lw?p=preview

【讨论】:

    【解决方案2】:

    不清楚您为什么要以这种方式获得服务?

    很确定你使用的语法是创建一个新的注入器,如果你想获得现有的注入器,那么你会使用类似的东西:

    angular.element(document).injector()

    即使我仍然想知道您为什么不正常注入服务。 https://docs.angularjs.org/api/ng/function/angular.injector


    啊,我现在看到您正在尝试在 Angular 上下文之外获取它...上面的 sn-p 将起作用,但认为您最好将通知代码包装在服务中而不是尝试使用 angular Angular 之外的东西将其他东西“纳入”或搜索为您工作的现有模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 2016-07-05
      相关资源
      最近更新 更多