Search code examples
angularjsbroadcast

angularjs $boadcast and $on doesn´t work from angular.injector


I´m trying to call a function into a Controller when received a Push Notification, passing for a $broadcast / factory, but the broadcast doesn´t work when calling by the angular.injector, here a peace of my code:

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

}


Solution

  • Not sure if it is best, but it works:

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

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