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

查看:83
本文介绍了在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 并运行previous监听器。

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

下面是一个活生生的例子:<一href=\"http://plnkr.co/edit/CpKtR5R357tEP32loJuG?p=$p$pview\">http://plnkr.co/edit/CpKtR5R357tEP32loJuG?p=$p$pview

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

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

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