【问题标题】:how to bind html in angular v1.2如何在 Angular v1.2 中绑定 html
【发布时间】:2013-09-12 20:35:17
【问题描述】:

我试图在 angularJS 中创建一个博客,在帖子消息部分我想从 json 获取消息并将其添加到这样的内容 div

<div class="content">
    {{json.message}}
</div>

现在我的 div 中有一个段落,它实际上是这样的 html 代码

<p>this is my message</p>

但是当我这样做时,我会在屏幕上看到这个

&lt;p&gt;this is my message&lt;/p&gt;

作为文本。我知道在以前的版本中我可以使用 ng-bind-html-unsafe 但我使用的是 angularJS v1.2。谁能告诉我类似于 ng-bind-html-unsafe 的代码,以便我可以在 v1.2 中进行这项工作? 谢谢你,丹尼尔!

【问题讨论】:

  • 好吧,我该死的 bing 已被用作动词。也许你的意思是绑定?

标签: javascript html angularjs


【解决方案1】:

您可以在 1.2 中使用Strict Contextual Escaping services ($sce)

控制器:

function myCtrl($scope,$sce) {
    $scope.myHtml = $sce.trustAsHtml('<span>Hello World!</span>');
}

模板:

<div ng-app ng-controller="myCtrl">
    <div ng-bind-html="myHtml"></div>
</div>

示例:http://jsfiddle.net/TheSharpieOne/GKnrE/1/

【讨论】:

  • 非常感谢您,这很完美!还要感谢@Problematic
【解决方案2】:

您需要注入并使用$sce 服务将其标记为受信任的HTML,然后使用ng-bind-html 指令(plunkr):

app.js:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $sce) {
  $scope.name = $sce.trustAsHtml('<p>Hello World</p>');
});

index.html:

<body ng-controller="MainCtrl">
    <div class="content" ng-bind-html="name"></div>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2020-05-30
    • 2018-02-26
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多