【问题标题】:Rendering html in Angular with Directive使用指令在 Angular 中渲染 html
【发布时间】:2013-09-12 03:49:31
【问题描述】:

我从所见即所得编辑器的输出中将 html 数据存储在我的数据库中。 html 还存储一些指令的 html。其中之一是 ui-bootstrap 工具提示:

<span tooltip-placement="left" tooltip="On the Left!">Tooltip text here</span>

我可以使用绑定让任何其他 html 元素工作:

<div ng-bind-html-unsafe="html.content"></div>

但是带有指令引用的 html 不与实际指令交互。

如何让指令生效?

我是否必须编译 html 或类似的东西?

【问题讨论】:

    标签: javascript angularjs compiler-directives


    【解决方案1】:

    是的,由于您尝试呈现的标记包含指令,因此您需要对其进行编译,以便 Angular 处理它们。

    您可以创建一个为您执行此操作的指令:

    app.directive('htmlRender', function($compile) {
      return {
        restrict: 'E',
        scope: { html: '@' },
        link: function(scope, element) {
          scope.$watch('html', function(value) {
            if (!value) return;
    
            var markup = $compile(value)(scope);
            element.append(markup);
          });
        }
      };
    });
    

    Plunkerhere.

    【讨论】:

      【解决方案2】:
      Do I have to compile the html or something like that?
      

      是的,您需要编译 HTML,因为 Angular 只会将以下内容视为简单的 html

      <div ng-bind-html-unsafe="html.content"></div>
      

      检查下面是 $compile 的文档

      $complie documenation

      【讨论】:

      • 我设法制作了一个简单的指令来编译给出的 html 值,然后简单地将内容放在元素中 - 编译文档在这方面非常有用
      猜你喜欢
      • 2013-04-01
      • 1970-01-01
      • 2014-09-10
      • 2021-05-13
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多