Search code examples
angularjsexternalbroadcastrootscope

Angular - can I $broadcast a message from outside an angular app?


I have a scenario where I need non-angular code (in this case Facebook and Twitter JS sdk's) to broadcast an event that angular controllers can listen to. Why? After the initial page load, I load and revise content in the page via AJAX. The content has multiple like/tweet buttons attached (like a front page of blog/aggregator). I'd like to add event hooks when a click occurs on either Facebook "Like" button or Twitter "Share" button - there are a few of those in the page, and each is changing whenever new content is fetched (again, via ajax).

Now, the SDK's handle this differently:

Twitter

twttr.events.bind('click', function(event){
    // here I'd like to somehow
    // $rootScope.$broadcast("twitter:clicked", event.currentTarget)
});

Facebook

FB.Event.subscribe("edge.create", function(resp) {
    // here I'd like to somehow
    // $rootScope.$broadcast("facebook:clicked", resp)
});

some controller

app.controller("SomeController", ['$scope', function($scope) {
    $scope.$on("facebook:clicked", function(event, resp) {
        // do something with resp
    });

    $scope.$on("twitter:clicked", function(event, target) {
        // do something target
    });
}])

The idea is to bind these event handlers once and then deal with the broadcasted message in the relevant controllers, even though these controllers are re-created whenever new content is fetched.

So basically, what I'm looking for is a way to hook into an existing and already initialized angular app's $rootScope and $broadcast a message, despite not being a part of the app. Hope this makes sense. Thanks.


Solution

  • You could bind to the other applications inside Angular code (in a directive that creates the links most probably). This way you have access to the $rootScope.

    Or, if you bootstrap your application manually, you can keep a reference to the injector and get the $rootScope:

    var injector = angular.bootstrap(element, ["myAppModule", ...]);
    var $rootScope = injector.get("$rootScope");
    

    In any case don't forget to call $apply after the external event.