Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Trigger directive from controller call

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?

like image 587
badaboum Avatar asked Jan 31 '14 10:01

badaboum


People also ask

How to call directive from controller in AngularJS?

Inside the directive it is creating an updateMap() method on the scope object in the directive and then calling the setFn() method which is mapped to the $scope. setDirectiveFn() method by this line: <map set-fn="setDirectiveFn(theDirFn)"></map> in your HTML and this line: scope: { setFn: '&' } in your directive.


1 Answers

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/

like image 102
Jeremy Likness Avatar answered Sep 25 '22 04:09

Jeremy Likness