AngularJS:将属性值从一个指令传递给被转移的指令

AngularJS:将属性值从一个指令传递给被转移的指令,angularjs,angularjs-directive,angularjs-scope,transclusion,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-d

我有一种情况,我必须创建一个带有一些提示的容器指令。。然后我有一个可以包装到容器指令中的指令列表

大概是这样的:

<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>
让我们假设这两个指令在一起具有不同且不相关的功能

某些指令

.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';
            };
        }
    }
});
其他指令

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

默认情况下,角度范围从父范围继承。不幸的是,对于角度默认转换,容器和转换的内容之间没有子/父关系

您可以尝试自定义转换

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


默认情况下,角度范围从父范围继承。不幸的是,对于角度默认转换,容器和转换的内容之间没有子/父关系

您可以尝试自定义转换

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


阅读更多关于AngularJS$scope继承的信息。也许这篇文章会帮助你,谢谢你的提示:)我想我也读过了。阅读更多关于AngularJS$scope继承的信息。也许这篇文章会帮助你谢谢你的提示:)我想我也读过了。这太棒了,谢谢你!我可以很容易地把它调整到我需要的程度。我知道ng transclude创建了同级作用域,我不知道如何绕过它。太好了,太好了,谢谢!我可以很容易地把它调整到我需要的程度。我知道ng transclude创建了同级作用域,我不知道如何绕过它。这太完美了。