1

I have a situation where I have to create a container directive with some bells and whistles.. and then I have a list of directives that can be wrapped into that container directive.

Something like this:

<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>

Is there any way in which I can make <some-directive> and <some-other-directive> aware of the foo and/or bar attributes values of the directive they are transcluded in?

Basic theContainer directive

.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
                };
            };
        }
    }
});

Let's presume that these two directives have different and unrelated function all together

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';
            };
        }
    }
});

someOtherDirective

.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

默认情况下,角度范围从父范围继承。不幸的是,使用角度默认嵌入,容器和嵌入内容之间没有子/父关系。

您可以尝试自定义嵌入。

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 回答