2

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

我有一个字符串如下

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

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

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

4

4 回答 4

5

您可以使用 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>

演示

于 2016-11-10T06:15:20.237 回答
3

您可以使用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>

于 2016-11-10T06:20:19.320 回答
2
<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>';
    }]);

从这里下载 sanitize.js

于 2016-11-10T06:16:37.930 回答
1

AngularJS

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

HTML

<div ng-bind-html="string"> </div>
于 2016-11-10T06:19:53.843 回答