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

谁都会走 提交于 2020-01-03 11:50:51

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/19197846/angular-can-i-broadcast-a-message-from-outside-an-angular-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!