【问题标题】:Angular multiple transclude dynamic number of elements角度多重嵌入动态元素数量
【发布时间】:2016-05-11 22:48:58
【问题描述】:

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

请注意,在实现多重嵌入的指令声明中,我必须先了解声明时将被嵌入的项目数量。

有没有办法在链接中(或使用变通方法)做这样的事情,这将保持与当前嵌入提供的相同功能?

【问题讨论】:

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


    【解决方案1】:

    不幸的是,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>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2020-07-21
      • 2016-09-26
      • 1970-01-01
      • 2019-01-07
      • 2020-09-14
      • 1970-01-01
      相关资源
      最近更新 更多