角 - 我可以从$的角度应用外广播消息? [英] Angular - can I $broadcast a message from outside an angular app?

查看:173
本文介绍了角 - 我可以从$的角度应用外广播消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我需要无棱角code(在这种情况下,Facebook和Twitter的JS SDK的)广播的事件角控制器可以听。为什么?初始页面加载后,加载和通过AJAX修改页面内容。内容有多个像连接(如博客/聚合的头版)/鸣叫按钮。我想补充事件挂钩时,点击任一Facebook的Like按钮或Twitter的共享按钮出现 - 也有少数的页面,每个正在改变,每当新的内容被取出(同样,通过AJAX )。

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

现在,SDK的处理这个问题是不同的:

Now, the SDK's handle this differently:

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

部分控制器

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.

所以基本上,我正在寻找的是挂接到现有的和已初始化的角度应用程序的 $ rootScope $广播的方式的消息,尽管不是应用程序的一部分。希望这是有道理的。谢谢你。

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.

推荐答案

您可以结合角code里面的其他应用程序(在创建该环节最可能是指令)。这样,您有机会获得 $ rootScope

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.

或者,如果手动引导你的应用程序,你可以保持到喷油器的引用,并获得 $ 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.

这篇关于角 - 我可以从$的角度应用外广播消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆