我在 SO 中检查了答案,但找不到令人满意的答案。所以在这里我问:
我有一个字符串如下
var string = "With this you have agreed with the <a href='#'>rules and condition</a>"
我需要将其呈现为字符串(用于文本部分)和 HTML(用于 HTML 部分)。
我如何在AngularJs中实现这一点?我尝试过,$compile
但它对我不起作用,它在页面上输出看似缩小的代码块。
我在 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>
您可以使用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>
<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
$scope.string = "With this you have agreed with the <a href='#'>rules and condition</a>"
<div ng-bind-html="string"> </div>