1

いくつかの機能を備えたコンテナー ディレクティブを作成しなければならない状況があります。そして、そのコンテナー ディレクティブにラップできるディレクティブのリストがあります。

このようなもの:

<the-container foo="bell" bar="whistle">

    <some-directive></some-directive>

</the-container>


<the-container foo="potato" bar="tomato">

    <some-other-directive></some-other-directive>

</the-container>

それらがトランスクルージョンされているディレクティブのand/or属性値を作成<some-directive><some-other-directive>て認識できる方法はありますか?foobar

基本的な theContainer ディレクティブ

.directive("theContainer", function() {
    return {
        restrict: "E",
        replace: true,
        transclude: true,
        scope: true,
        templateUrl: "theContainer.html",
        compile: function(element, attrs) {
            return function(scope, element, attrs) {
                scope.containerAttrs = {
                    foo: attrs.foo,
                    bar: attrs.bar
                };
            };
        }
    }
});

これらの 2 つのディレクティブには、まったく無関係の異なる機能があると仮定しましょう。

someDirective

.directive("someDirective", function() {
    return {
        restrict: "E",
        scope: true,
        templateUrl: "someDirective.html",
        controller: function($scope, $element, $attrs) {},
        compile: function(element, attrs) {
            return function(scope, element, attrs) {
                // I need the value from theContainer foo and bar here
                // or anywhere in this directive for starters
                foo = 'bells';
                bar = 'whistles';
            };
        }
    }
});

someOther指令

.directive("someOtherDirective", function() {
    return {
        restrict: "E",
        scope: true,
        templateUrl: "someOtherDirective.html",
        controller: function($scope, $element, $attrs) {
            // I need the value from theContainer foo and bar here
            // or anywhere in this directive for starters
            foo = 'potato';
            bar = 'tomato';
        }
    }
});
4

1 に答える 1

5

angular のスコープは、デフォルトで親スコープから継承します。残念ながら、Angular のデフォルトのトランスクルージョンでは、コンテナーとトランスクルードされたコンテンツの間に子/親の関係はありません。

カスタムトランスクルージョンを試すことができます。

compile: function(element, attrs, linker) {
      return function(scope, element, attrs) {
        scope.containerAttrs = {
          foo: attrs.foo,
          bar: attrs.bar
        };
        linker(scope, function(clone) { //bind scope anyway you want
          element.append(clone); // add to DOM anywhere you want
        });
      };
}

ng-transclude:カスタム トランスクルージョンを行うときは、テンプレートで削除することを忘れないでください。

デモ

于 2014-03-02T09:26:47.607 に答える