【问题标题】:Render angular code within a ng-bind-html在 ng-bind-html 中渲染 Angular 代码
【发布时间】:2015-02-11 00:12:34
【问题描述】:

我正在尝试使用显着和角度来呈现 github 自述文件。与解析 markdown 相关的一切工作正常,但不幸的是,产品所有者对应用程序有更多的期望。

他希望能够将 youtube 视频和 html 表单放入自述文件中。我目前正在使用Brandly 制作的Youtube-embed directive,但不幸的是它没有在我们的页面中呈现。

我正在使用将ng-bind-html$sce.trustAsHtml 结合使用的脚本来解析页面中的html。正常的 HTML 可以很好地拾取(表单标签和其他东西),但有角度的东西(例如 youtube 指令)不是。

我还注意到 ng-clickng-submit 等角度指令不起作用。 有谁知道如何在使用 ng-bind-html 的 Angular 应用程序中解析的 html 中进行 Angular 工作?

这是一个关于如何将 html 解析为模板的代码示例:

JS:

case 'markdown':
    $scope.fileContent = $sce.trustAsHtml(remarkable.render(content));
break;

HTML:

<pre class="fileContent"><code ng-bind-html="fileContent"></code></pre>

我添加了一个 Plunker example 来解决我遇到的问题,你可以看到它永远不会执行我在表单中添加的 ng-submit

~弓箭

【问题讨论】:

标签: javascript html angularjs ng-bind-html


【解决方案1】:

使用来自 Angular 站点的示例指令:https://docs.angularjs.org/api/ng/service/$compile

angular.module('compileExample', [], function($compileProvider) {
    // configure new 'compile' directive by passing a directive
    // factory function. The factory function injects the '$compile'
    $compileProvider.directive('compile', function($compile) {
      // directive factory creates a link function
      return function(scope, element, attrs) {
        scope.$watch(
          function(scope) {
             // watch the 'compile' expression for changes
            return scope.$eval(attrs.compile);
          },
          function(value) {
            // when the 'compile' expression changes
            // assign it into the current DOM
            element.html(value);

            // compile the new DOM and link it to the current
            // scope.
            // NOTE: we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(element.contents())(scope);
          }
        );
      };
    });
  })
  .controller('GreeterController', ['$scope', function($scope) {
    $scope.name = 'Angular';
    $scope.html = 'Hello {{name}}';
  }]);

那么你就可以像在中那样使用它了

<p compile="fileContent"></p>

【讨论】:

  • 谢谢,问题解决了,没想到这么简单。 :D
猜你喜欢
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 2015-05-06
相关资源
最近更新 更多