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