簡體   English   中英

在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

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

AngularJS

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

HTML

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM