从角广播到一个jQuery监听器 [英] Broadcast from Angular to a jQuery Listener
问题描述
试图让AngularJS广播自定义事件的jQuery是监听。
在jQuery的我有类似这样:
的$(document)。在(myCustomEvent功能(事件数据){
$(本)的.text(data.myName +,您好!);
});
在我有这样的事情在AngularJS:
$ rootScope $广播('myCustomEvent',数据);
应该不是jQuery的能够监听广播的AngularJS是广播或者是绑AngularJs只有这个:
$范围。美元。('myCustomEvent',函数(事件数据){
http://plnkr.co /编辑/ WFERKW?p = preVIEW
在一般情况下,这将触发DOM元素上事件将DOM树鼓泡到目标单元的所有的父母。所以,你可以注入 $元素
服务在您的控制器和触发事件就可以了。
//文件作为`$ element`家长将收到此事件
$(文件)。在('myCustomEvent',函数(事件数据){
的console.log(数据);
});
//在控制器
$ element.trigger('myCustomEvent',{MYNAME:史蒂夫·乔布斯'});
注意
-
$元素
服务不能被注入每一个地方。在控制器中,可以使用$元素
,在一个指令,你应该使用元素
参数的链接功能。 -
您也可以使用
$文件
服务触发事件
上。 -
Besure包括jQuery的角库之前,让jQuery的方法将被自动包含在
$元素
和$文件
服务。
Trying to get AngularJS to broadcast a custom event that jQuery is listening for.
In the jQuery I have something similar to this:
$( document ).on( "myCustomEvent", function( event, data ) {
$( this ).text( data.myName + ", hi there!" );
});
In the AngularJS I have something like this:
$rootScope.$broadcast('myCustomEvent', data);
Shouldn't jQuery be able to listen for the broadcast that AngularJS is broadcasting or is tied to AngularJs only with this:
$scope.$on.('myCustomEvent', function(event,data) {
Demo http://plnkr.co/edit/WFERKW?p=preview
In general, event that is triggered on a DOM element will bubbling up the DOM tree to all parents of target element. So you can inject $element
service in your controller and trigger event on it.
// Document as a parent of `$element` will receive this event
$(document).on('myCustomEvent', function(event, data) {
console.log(data);
});
// In controller
$element.trigger('myCustomEvent', {myName: 'Steve Jobs'});
Attention
$element
service cannot be injected every where. In a controller, you can use$element
, in a directive, you should useelement
argument from link function.You could also use
$document
service to triggerevent
on.Besure to include jQuery before Angular library, so jquery method will be automatically included in
$element
and$document
services.
这篇关于从角广播到一个jQuery监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!