Question

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.

Était-ce utile?

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

Autres conseils

You can wrap the FB and Twitter API in directives, which can generate the necessary html (using template) for creating any FB or Twitter component.

In the directive link function you can you initialize the sdk component and bind to its events and then do a broadcast or emit as directive would get scope of parent on which it is declared.

Otherwise if you want to gain access to the scope of a element in angular look at this SO post Call Angular JS from legacy code

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top