Broadcast from Angular to a jQuery Listener

前端 未结 2 1480
清歌不尽
清歌不尽 2021-01-17 21:05

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( \         


        
2条回答
  •  粉色の甜心
    2021-01-17 21:37

    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.

提交回复
热议问题