2

AngularJS には、基本的なトランスクルージョンを持つディレクティブがあります。私はそれを使用するときに通常、入力またはテキストエリアがトランスクルードされることを知っています。もしあれば、そのモデルの変更を $watch したいと思います。しかし、トランスクルージョンされたコンテンツの属性にはアクセスできず、ディレクティブが呼び出されるルート要素の属性にしかアクセスできません。トランスクルージョンされたスコープも同様です (おそらく scope.$$nextSibling が役立つかもしれませんが、何かが地獄への道だと教えてくれます :) )。

ディレクティブが呼び出される要素に別のパラメータ(属性)を追加せずにそれを行う方法はありますか?

ディレクティブ テンプレート

<div ng-transclude>
    <someContent>...</someContent>
    <!-- HERE IS INPUT TRANSCLUDED -->
</div>

ディレクティブの使用

<div my-directive="somedata">                           //this attribs are accessable
    <input ng-model="iWantToWatchThisInMyDirective" />  //but i want to access this also
</div>
4

2 に答える 2

0

これが私の解決策です:

2 番目のディレクティブを作成しました: Input (Element に制限されているため、すべての入力に 1 つあります)。Input ディレクティブでは、要素のスコープへのすべての変更をブロードキャストします。

link: function (scope, element: JQuery, attrs: ng.IAttributes) {
  if(typeof attrs.ngModel !== "undefined") {
    scope.$watch(attrs.ngModel, function (newValue, oldValue) {
      scope.$broadcast('valueChanged'+scope.$id, newValue, oldValue);
    });
  }
}

scope.$id は、イベント名がすべての入力に対して一意であることを確認するために使用されます。

さて、他のディレクティブでは、入力を変更するイベントをリッスンできます。

link: function (scope, element:JQuery, attrs:ng.IAttributes) {
  //My input is last child everytime..
  var children = element.find("input");
  var lastInput = angular.element(children[children.length - 1]); 
  var lastInputScope = lastInput.scope();

  var unregister = lastInputScope.$on('valueChanged' + lastInputScope.$id, 
                                      function (event, newValue, oldValue) {
    //do whatever you want...
  });

  scope.$on('$destroy', function () {
    unregister();
  });
}
于 2013-07-26T09:12:48.350 に答える