AngularJS:将属性值从一个指令传递给transcluded一个

GRo*_*ing 1 angularjs transclusion angularjs-directive angularjs-scope

我有一种情况,我必须创建一个带有一些花里胡哨的容器指令..然后我有一个可以包装到该容器指令中的指令列表.

像这样的东西:

<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>
Run Code Online (Sandbox Code Playgroud)

有没有什么办法中,我可以<some-directive><some-other-directive>认识的foo和/或bar属性,它们在transcluded指令的价值观?

基本的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
                };
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

让我们假设这两个指令一起具有不同且无关的功能

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';
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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';
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Kha*_* TO 5

默认情况下,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
        });
      };
}
Run Code Online (Sandbox Code Playgroud)

注意:记得ng-transclude在进行自定义转换时在模板中删除,

DEMO