角多个元素的动态数量

kcl*_*m06 5 javascript angularjs angularjs-directive angularjs-ng-transclude

Angular 1.5可以进行多重遮挡

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

为了进一步说明,我希望能够执行以下操作:

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

请注意,在实现多重转换的指令声明中,我必须具有在声明时将要转换的项目数量的先验知识。

有没有一种方法可以在链接中(或使用解决方法)执行类似的操作,而该功能将保持与当前包含的功能相同?

Ovi*_*lha 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 = [];

...
Run Code Online (Sandbox Code Playgroud)

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

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

在组件中我们启用动态嵌入:

...
selector: 'myCustomComponent',
template: template,
transclude: 'dynamic',
bindings: {
  transcludeDynamic: '<'
}
Run Code Online (Sandbox Code Playgroud)

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

例如:

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

公关: https: //github.com/angular/angular.js/pull/14227