AngularJS Trigger directive from controller call

后端 未结 1 512
走了就别回头了
走了就别回头了 2020-12-28 22:41

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条回答
  • 2020-12-28 23:28

    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/

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