【问题标题】:Angular $compile for dynamic contentAngular $compile 用于动态内容
【发布时间】:2017-01-21 15:03:15
【问题描述】:

使用 Angular 1.5,我想使用通用的“覆盖”组件来显示模式中的其他组件。我想传入要在叠加层中呈现的其他组件。

我以为我可以在我的控制器中使用 $compile,但是组件没有渲染:

在我的控制器中:

ctrl.appendComponent = function(component_type) {
    ctrl.$content.empty(); // this is the overlay element
    var component = '<' + component_type + '></' + component_type + '>';
    ctrl.$content.append($compile(component)($scope));
};

我已经创建了我想要传入的组件,例如“foo”并且在 DOM 中只获取了一个空元素:

<foo></foo>

尽管,在 foo 组件的模板中,我有:

<h1>header</h1>
<p>body</p>

并期待看到:

<foo>
  <h1>header</h1>
  <p>body</p>
</foo>

【问题讨论】:

  • 什么是$content?请提供MCVE,最好是小提琴/plunk。
  • 另外你是如何创建组件的?使用 1.5 组件(.. 或使用 .directive(.. with replace:true?

标签: angularjs angularjs-compile angularjs-components angularjs-1.5


【解决方案1】:

这是一个示例,但看起来您正在做同样的事情。我建议简化您的代码,可能是某些东西没有返回您认为的内容。

                link: function(scope, iElem, tAttrs){
                            var html = "<div>hello</div>";

                            var content = $compile(html)(scope);
                            iElem.append(content);
                }

【讨论】:

  • 谢谢@Darin。查看我的代码后,我意识到我使用 kebab-case 而不是 camel-case 定义了我传入的组件:App.component('foo-bar', ... 而不是:App.component('fooBar', ...
猜你喜欢
  • 1970-01-01
  • 2016-05-30
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多