0

ページで複数回使用しているディレクティブがある場合、1 つのディレクティブが別のディレクティブと通信するにはどうすればよいでしょうか?

親子関係でディレクティブを連鎖させようとしています。ディレクティブ A をクリックすると、ディレクティブ B をフィルター処理して、ディレクティブ A で選択したアイテムの子のみを持つようにします。この場合、ページには無数のディレクティブと関係が存在する可能性があります。

通常、ディレクティブ A がその子のそれぞれでフィルター メソッドを呼び出し、各子がその子を呼び出して、階層を下方向にフィルター処理し続けます。

しかし、あるディレクティブから別のディレクティブへのメソッドの呼び出しが可能かどうかはわかりません。

ありがとう

4

2 に答える 2

1

ディレクティブコントローラーを探しているようです。ディレクティブのパラメーターを使用してrequire:、別のディレクティブのコントローラーをプルできます。次のようになります。

app.directive('foo', function() {
  return {
    restrict: 'A',
    controller: function() {
        this.qux = function() {
          console.log("I'm from foo!");
        };
    },
    link: function(scope, element, attrs) {

    }
  };
});

app.directive('bar', function() {
    return {
        restrict: 'A',
        require: '^foo',
        link: function(scope, element, attrs, foo) {
            foo.qux();
        }
    };
});

angular docs から、require で使用できるシンボルとその機能を以下に示します。

(no prefix) - Locate the required controller on the current element.
? - Attempt to locate the required controller, or return null if not found.
^ - Locate the required controller by searching the element's parents.
?^ - Attempt to locate the required controller by searching the element's parents, or return null if not found.

これが私の例のjsbinです。http://jsbin.com/aLikEF/1/edit

必要に応じて機能する可能性のある別のオプションは、各ディレクティブが監視を設定して操作できるサービスを用意することです。たとえば、directive1 はサービス内のプロパティを監視し、変更に応答し、そのプロパティを変更できるボタンを設定することもできます。次に、directive2 もサービスを監視して変更することができ、どのように設定しても相互に応答します。その jsbin も必要な場合は、お知らせください。

これが役立つことを願っています!

于 2013-08-20T06:46:18.870 に答える
0

ディレクティブがそれぞれ参照できるサービスにすべてのデータを入れてみてください。

何かのようなもの:

app.factory('selectedStuffService', function(){
    var allItems = [];
    var selectedItems = [];

    function addSelectedItem(item){
         selectedItems.push(item);
    }

    return {
        allItems: allItems,
        selectedItems: selectedItems,
        addSelectedItem: addSelectedItem
    }
}

ディレクティブ A の相互作用は selectedItems 配列の値を変更し、ディレクティブ B はそれにバインドできます。サービスに他のメソッドを簡単に追加して、必要に応じてアイテムをフィルタリング/操作できます。サービスを使用するディレクティブは、他のディレクティブによって行われた変更に基づいて更新できる必要があります。

于 2013-08-20T14:15:50.620 に答える