Angularjs 嵌入式数据应显示一个链接



我有来自包含href链接的服务器的数据。 当我将其嵌入模板中时,它显示的是代码而不是链接。 就像HTML没有被解释一样。这是代码笔。

JS:

$scope.link = "<a href=''></a>";

和模板

<p>{{link}}</p>

此代码如何显示带有链接的段落?

你需要

使用 ng-bind 和 $sce。 $sce会告诉你的应用 HTML 是可信的。话虽如此,如果你不信任你得到的HTML,你应该小心这样做(即,如果这是来自你不一定信任的用户)。您可能还想查看对此进行消毒。

.HTML

<div ng-app="SOAngular" ng-controller="mainController">
  This should be a link and not pure text.
  <p ng-bind-html="link"></p>
</div>

.JS

app.controller('mainController', function($scope,$sce) {
  $scope.link = $sce.trustAsHtml("<a href=''>test</a>");
});

我在这里用解决方案分叉了您的示例:http://codepen.io/anon/pen/WxvOEX

引用

  • https://docs.angularjs.org/api/ng/service/$sce
  • https://docs.angularjs.org/api/ng/directive/ngBindHtml

你需要使用 ng-bind-html

<p ng-bind-html="link"></p>

也请参考$sce,因为您需要

使用
$scope.link = $sce.trustAsHtml("<a href=''></a>");

假设你有一个包含 html 的作用域变量!

$scope.link = "<h1>Big Nice Link here</h1>";

您应该能够这样输出它

<div ng-bind-html-unsafe="someHTML"></div>

..在您的情况下应该是这样的

[...]

<div class="item item-text-wrap" ng-bind-html-unsafe="link"></div>

[...]

也可以尝试这种方式:

[...]

<div class="item item-text-wrap" ng-bind-html="link"></div>

[...]

最新更新