从角广播到一个jQuery监听器 [英] Broadcast from Angular to a jQuery Listener

查看:258
本文介绍了从角广播到一个jQuery监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让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:史蒂夫·乔布斯'});

注意


  1. $元素服务不能被注入每一个地方。在控制器中,可以使用 $元素,在一个指令,你应该使用元素参数的链接功能。


  2. 您也可以使用 $文件服务触发事件上。


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

  1. $element service cannot be injected every where. In a controller, you can use $element, in a directive, you should use element argument from link function.

  2. You could also use $document service to trigger event on.

  3. Besure to include jQuery before Angular library, so jquery method will be automatically included in $element and $document services.

这篇关于从角广播到一个jQuery监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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