AngularJS 中的指令到指令通信? [英] Directive-to-directive communication in AngularJS?

查看:19
本文介绍了AngularJS 中的指令到指令通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道您可以在指令中设置控制器,并且其他指令可以调用该控制器上的函数.这是我当前的指令的样子:

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 looks like:

app.directive("foobar", function() {
  return {
    restrict: "A",
    controller: function($scope) {
      $scope.trigger = function() {
        // do stuff
      };
    },
    link: function(scope, element) {
     // do more stuff
    }
  };
});

我知道我可以这样称呼它:

I know that I could call it like this:

app.directive("bazqux", function() {
  return {
    restrict: "A",
    require: "foobar",
    link: function(scope, element, attrs, fooBarCtrl) {
        fooBarCtrl.trigger();
    }
  };
});

但是,我希望能够从任何指令调用触发器,而不仅仅是我自己的自定义指令,如下所示:

However, I want to be able to call trigger from any directive, not just my own custom ones, like this:

<button ng-click="foobar.trigger()">Click me!</button>

如果这不起作用,有没有办法引入第三个指令来实现它?像这样吗?

If that doesn't work, is there a way to bring in a third directive to make it happen? Like this?

<button ng-click="trigger()" target-directive="foobar">Click me!</button>

谢谢!

推荐答案

在任何组件之间完成应用程序范围通信的一种简单方法是使用全局事件(从 $rootScope 发出).例如:

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>

在这里,您从子作用域发出一个事件,但它最终会到达 $rootScope 并运行前一个侦听器.

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

这是一个活生生的例子:http://plnkr.co/edit/CpKtR5R357tEP32loJuG?p=preview

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

这篇关于AngularJS 中的指令到指令通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆