![](/img/trans.png)
[英]How to display string HTML containing inline style tag from angular component
[英]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>
您可以使用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>
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>';
}]);
從這里下載sanitize.js
$scope.string = "With this you have agreed with the <a href='#'>rules and condition</a>"
<div ng-bind-html="string"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.