在 Angular 中显示包含 HTML 标记的字符串

Display string containing HTML tag in Angular

我在 SO 中查看了答案,但找不到满意的答案。所以我在这里问:

我有一个字符串如下

var string = "With this you have agreed with the <a href='#'>rules and condition</a>"

我需要将其呈现为字符串(对于文本部分)和 HTML(对于 HTML 部分)。

如何在 AngularJs 中实现此目的?我尝试使用 $compile 但它对我不起作用,它在页面上输出了看似缩小的代码块。

您可以使用 ng-bind-html,

angular.module('myapp', ['ngSanitize'])
.controller('foo', function($scope) {
    $scope.bar = "With this you have agreed with the <a href='#'>rules and condition</a>";
});

<div ng-controller="foo">    
    <div ng-bind-html="bar"></div>    
</div>

DEMO

<html>
    <div
      ng-bind-html="myHTML">
    ...
    </div>
<html>

代码:

angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.myHTML =
         'I am an <code>HTML</code>string with ' +
         '<a href="#">links!</a> and other <em>stuff</em>';
    }]);

here 下载 sanitize.js

AngularJS

$scope.string = "With this you have agreed with the <a href='#'>rules and condition</a>"

HTML

<div ng-bind-html="string"> </div>

您可以使用 ng-bind-html 指令,如下所示。要使用它,您必须包含 ngSanitize 模块和相关的 js 文件。

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

app.controller('TestController', function($scope) {
  $scope.string = 'With this you have agreed with the <a href="#">rules and condition</a>';
});

angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.8/angular-sanitize.min.js"></script>
<div ng-controller="TestController">
  <span ng-bind-html="string"></span>
</div>