繁体   English   中英

如何使用 angular 在 html 中绑定 html 标签

[英]How to bind html tags in html using angular

HTML

<div><code><pre>{{out_html}}</pre></code></div>

AngularJS

$scope.out_html = "<p style='color:red'>John Smith</p>";

我想在 html 浏览器中以红色显示“p”标签名称“John smith”。 但这里显示的是 html 代码,而不是红色的“John Smith”。

笨蛋

你可以像这样绑定它:

<div>
  <code>
    <pre ng-bind-html="out_html" style="color:red;"></pre>
  </code>
</div>

对于颜色,您可以设置<pre>元素的样式。

ng-bind-html 指令是一种将内容绑定到 HTML 元素的安全方式。 更多详情: https://www.w3schools.com/angular/ng_ng-bind-html.asp

是的,Angular 默认清理绑定的表达式。 为了防止您可以使用 ngBindHtml: https://docs.angularjs.org/api/ng/directive/ngBindHtml

但是,如果这只是样式问题,为什么不使用ngClass呢? https://docs.angularjs.org/api/ng/directive/ngClass

您可以使用ng-bind-html指令在 angular js 中绑定 html,

这是你工作的笨蛋

<code>
      <pre>
        <p ng-bind-html="out_html"></p>
      </pre>
</code>

您可以将 p 标签值和 p 颜色分开,只需添加另一个变量/范围

HTML

<div><code><pre><p style='color:{{color}}'>{{value}}</p></pre></code></div>

AngularJS

$scope.value = "John Smith";
$scope.color = "red";

这是 angularjs 的安全预防措施。 这是为了确保不受欢迎的行为。 因此 Angular 将始终为您转义标签。 您可以做的是使用ng-bind-html但非常重要的是您首先“允许”将此字符串解释为与 trustAsHtml 一起使用的HTML

angular.module('test', []).controller('ctrl', function($scope, $sce) {
  $scope.out_html = "<p style='color:red'>John Smith</p>";
  $scope.trust = $sce.trustAsHtml;
});

<span ng-bind-html="trust(out_html)"></span></div>

这也是该问题的另一个线程: https://stackoverflow.com/a/28444859/8196542

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM