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

时间:2014-03-02 09:12:06

标签: angularjs angularjs-directive angularjs-scope transclusion

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

这样的事情:

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

有什么方法可以让<some-directive><some-other-directive>知道它们被转换的指令的foo和/或bar属性值?< / p>

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

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

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

1 个答案:

答案 0 :(得分: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
        });
      };
}

注意:在进行自定义转换时,请务必删除模板中的ng-transclude

DEMO