Directive-to-directive communication in AngularJS?

后端 未结 3 1032
长情又很酷
长情又很酷 2021-01-04 09:09

I already know that you can set up a controller within a directive, and that other directives can call the functions on that controller. Here\'s what my current directive lo

相关标签:
3条回答
  • 2021-01-04 09:17

    Sounds like you need an angular service. http://docs.angularjs.org/guide/dev_guide.services

    This will allow you to share functionality across directives.

    Here's a similar question: Sharing data between directives

    0 讨论(0)
  • 2021-01-04 09:33

    One simple way of accomplishing application-wide communication between any components would be to use global events (emitted from the $rootScope). For example:

    JS:

    app.directive('directiveA', function($rootScope)
    {
        return function(scope, element, attrs)
        {
            // You can attach event listeners in any place (controllers, too)
    
            $rootScope.$on('someEvent', function()
            {
                alert('Directive responds to a global event');
            });
        };
    });
    

    HTML:

    <button ng-click="$emit('someEvent')">Click me!</button>
    

    Here you're emitting an event from the child scope but it will eventually reach the $rootScope and run the previous listener.

    Here's a live example: http://plnkr.co/edit/CpKtR5R357tEP32loJuG?p=preview

    0 讨论(0)
  • 2021-01-04 09:37

    When talking on irc it turned out that the communication is unnecessary:

    I've got an attribute-restricted directive which performs some DOM manipulation on its parent element when it's "triggered"

    A solution is to keep the logic inside the same directive and just to apply the dom changes to the parent. http://jsfiddle.net/wt2dD/5/

    scope.triggerSmthOnParent = function () {
        element.parent().toggleClass('whatewer');
    }
    
    0 讨论(0)
提交回复
热议问题