12

ディレクティブ内にコントローラーを設定できること、および他のディレクティブがそのコントローラーの関数を呼び出すことができることは既に知っています。現在のディレクティブは次のようになります。

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

私はそれを次のように呼び出すことができることを知っています:

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

ただし、次のように、独自のカスタム ディレクティブだけでなく、任意のディレクティブからトリガーを呼び出せるようにしたいと考えています。

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

それがうまくいかない場合、それを実現するために 3 番目のディレクティブを導入する方法はありますか? このような?

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

ありがとう!

4

3 に答える 3

8

角度のあるサービスが必要なようです。http://docs.angularjs.org/guide/dev_guide.services

これにより、ディレクティブ間で機能を共有できます。

同様の質問があります:ディレクティブ間でデータを共有する

于 2013-05-18T20:35:40.290 に答える
6

コンポーネント間のアプリケーション全体の通信を実現する簡単な方法の 1 つは、グローバル イベント ($rootScope から発行される) を使用することです。例えば:

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は前のリスナーに到達して実行します。

実際の例を次に示します: http://plnkr.co/edit/CpKtR5R357tEP32loJuG?p=preview

于 2013-05-18T21:38:57.963 に答える