Angular JS – InteropService to broadcast events between different apps

angular.module("myApp.services")
    .service("interopService", ["$q", function ($q) {
        var _self = this;

        _self.broadcastEventToApp = function (appSelector, event, args) {
            return $q(function (resolve, reject) {
                var app = $(appSelector), injector;
                if (app.length > 0 && app.hasClass("ng-scope")
                    && !!(injector = app.injector())) {

                    var $rootScope = injector.get("$rootScope");
                    safeApply($rootScope, function () {
                        $rootScope.$broadcast(event, args);
                        resolve();
                    });
                } else {
                    reject();
                }
            });
        };

        _self.broadcastEvent = function (event, args) {
            var apps = $(".ng-scope").filter(function (i, e) {
                return $(e).parents(".ng-scope").length == 0;
            });

            apps.each(function () {
                _self.broadcastEventToApp(this, event, args);
            });
        };

        function safeApply($rootScope, callback) {
            var phase = $rootScope.$$phase;
            if (phase == '$apply' || phase == '$digest') {
                callback();
            } else {
                $rootScope.$apply(callback);
            }
        }
    }]);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s