Directive-to-directive communication in AngularJS?

后端 未结 3 1049
长情又很酷
长情又很酷 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: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:

    
    

    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

提交回复
热议问题