Angular multiple转换动态元素数

时间:2016-02-02 22:41:25

标签: javascript angularjs angularjs-directive angularjs-ng-transclude

Angular 1.5支持multi transclude

值得注意的是,能够将动态数量的项目转换为指令并在稍后的时间(例如在链接/编译中)声明这些转录的名称和位置是有用的。

为了进一步说明,我希望能够做类似的事情:

//Example usage of directive
<multi-slot-transclude-example>
<transclude1>TEST1</div>
<transclude2>TEST2</div>
<transclude3>TEST3</div>
<transclude4>TEST4</div>
.... dynamic number of items ...
</multi-slot-transclude-example>

//Example of directive that dynamically transcludes multiple items
angular.module("multiSlotTranscludeExample", [])
    .directive("directiveName", function(){
    return {
        restrict: 'E',
        transclude: {
            't1': '?transclude1',
            't2': '?transclude2',
            //I'd like this list to be able to be defined non-statically (e.g. in link)
        },
        template: '<div ng-repeat="n in transcludedElementList">'
        + '<div ng-transclude="t{{n}"></div>'
        + '</div>'
        };
})

请注意,在实现多转换的指令声明中,我必须事先了解声明它时将被转换的项目数。

是否有办法在链接(或使用变通方法)中执行此类操作,这将保留与当前提供的转换功能相同的功能?

1 个答案:

答案 0 :(得分:4)

不幸的是,Angular似乎没有提供任何非侵入性的方法。

但是,可以通过一些调整来实现。

我们需要介入angular.js的翻译插槽逻辑:

...

var slots = createMap();

$template = jqLite(jqLiteClone(compileNode)).contents();

// Small tweak to allow dynamic transclusion
if (directiveValue === 'dynamic') {
  directiveValue = $parse(templateAttrs.transcludeDynamic)();
}

if (isObject(directiveValue)) {

  // We have transclusion slots,
  // collect them up, compile them and store their transclusion functions
  $template = [];

...

这允许我们在组件的使用者中指定转换选项,如下所示:

<my-custom-component transclude-dynamic="{testSlot: 'test', testSlot2: 'test2'}">
  <test>something to transclude</test>
  <test2>then another slot content to transclude</test2>
</my-custom-component>

在我们启用动态转换的组件中:

...
selector: 'myCustomComponent',
template: template,
transclude: 'dynamic',
bindings: {
  transcludeDynamic: '<'
}

请注意,我们还绑定了转换信息,这使我们能够对其进行ng-repeat,ng-if和任何其他逻辑。

例如:

<div ng-repeat="(slot, name) in $ctrl.transcludeDynamic">
  <div ng-transclude="{{slot}}"></div>
  <hr>
  <div>something else</div>
</div>

PR:https://github.com/angular/angular.js/pull/14227