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?

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

What are the advantages of doing it this way over using the $broadcast/$on?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.