Broadcast from Angular to a jQuery Listener

前端 未结 2 1479
清歌不尽
清歌不尽 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.

    0 讨论(0)
  • 2021-01-17 21:40

    I've got to be a nay-sayer; don't do this. What you are doing, modifying the DOM based on an event, is literally what angular was built for. Bringing jQuery into the picture is unnecessary, and only adds complication. Look into ng-bind and ng-model to see how to update the DOM in response to your data changing.

    0 讨论(0)
提交回复
热议问题