【问题标题】:How to make ngIf work after transclusion?嵌入后如何使ngIf工作?
【发布时间】:2018-09-12 05:56:49
【问题描述】:

我有一个列表组件,我想在其中定义自定义列。这些列被嵌入到组件模板的行中。不幸的是,我不能在这种情况下使用 ngIf。

这是我的 myList 组件的 $postLink 函数:

const template = $templateCache.get('myList.tpl.html');
const jqTemplate = angular.element(template);
const row = angular.element(jqTemplate.children()[0]);

$transclude(clone => {
  row.append(clone);
  $element.html(jqTemplate.html());
});

$compile($element.contents())($scope);

这是最小样本的 plnkr:http://plnkr.co/edit/C9Rvs8NiTYsV3pwoPF6a

是因为terminal 属性吗?有人可以启发我为什么 ngIf 不能像预期的那样工作吗?

【问题讨论】:

  • 检查这个kylelieber.com/2016/04/angular-transclude-directive-and-ng-if(组件是一种特殊类型的指令,所以文章仍然有效)。我知道您要的是 ng-if,但您的案例适用于 ng-show/hide。显然,删除 dom 元素及其观察者与仅通过 css 隐藏它们在性能方面不同,但如果您没有大量的行/列,也许您可​​以省去头疼 :)
  • 您的链接实际上解决了整个问题,这是一个非常好的解决方案,是时候保存它了 :-)

标签: angularjs directive angularjs-ng-transclude


【解决方案1】:

我认为尝试在postLink 阶段执行操作为时已晚,因为它首先应用于子元素。

编译阶段似乎更合适。那里的事情更简单,您甚至不需要使用嵌入或克隆链接功能。范围在以后的状态中应用。

我提供了一个使用指令的解决方案,因为在这种情况下,我发现组件语法更加混乱。

app.directive('myList', function($templateCache){
    return {
        bindings: {
          list: '='
        },
        transclude: false,
        compile: function(tElement) {
            const template = $templateCache.get('myList.tpl.html');
            const jqTemplate = angular.element(template);
            var elemChildren = tElement.children('div');
            jqTemplate.children('.row').append(elemChildren);
            tElement.append(jqTemplate);
          return {};
        }

    }

});

http://plnkr.co/edit/MrLJmnMKxO8PVPkzE8KK?p=preview

【讨论】:

    猜你喜欢
    • 2018-03-09
    • 2018-01-12
    • 2017-03-13
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多