10

I want to trigger an AngularJS custom directive that contains jQuery instructions. How can it be done? I have read about emit function in the directive?

ideas?

chenrui
  • 8,910
  • 3
  • 33
  • 43
badaboum
  • 843
  • 2
  • 17
  • 28
  • 1
    http://stackoverflow.com/questions/16935095/correct-way-to-integrate-jquery-plugins-in-angular-js – Ismael Jan 31 '14 at 10:56

1 Answers1

24

You can use a service to communicate between the controller and the directive.

Service might look like this:

app.service("directiveService", function() {
    var listeners = [];
    return {
        subscribe: function(callback) {
            listeners.push(callback);
        },
        publish: function(msg) {
            angular.forEach(listeners, function(value, key) {
                value(msg);
            });
        }
    };
});

And the directive could respond to the service:

app.directive("jQueryDirective", function(directiveService) {
    directiveService.subscribe(function(msg) {
        // pretend this is jQuery 
        document.getElementById("example")
        .innerHTML = msg;
    });
    return {
        restrict: 'E'        
    };
});

Just substitute what I did for jQuery manipulation and you should have what you need.

Here's a working fiddle: http://jsfiddle.net/jeremylikness/wqXYx/

Jeremy Likness
  • 7,531
  • 1
  • 23
  • 25
  • 1
    What are the advantages of doing it this way over using the $broadcast/$on? – Strawberry Apr 30 '15 at 02:02
  • 3
    Broadcast creates a dependency on $scope as well as on $scope hiearchy. If you rely on that you have a lot of listeners being called that may or not be interested in the message, while an explicit service only targets the components that need it. It also makes it easier to test and is reusable and self-contained. – Jeremy Likness Apr 30 '15 at 17:54