在 AngularJS 中,可以在控制器中建立 HTML 片段並將它們呈現在視圖中。這對於動態生成清單或其他複雜的 UI 元素非常有用。
要實現此目的,首先建立一個模型屬性來保存 HTML 片段。在下面的範例中,我們建立一個「customHtml」屬性:
var SomeController = function () { this.customHtml = '<ul><li>render me please</li></ul>'; }
接下來,在視圖中使用ng-bind-html 指令將customHtml 屬性綁定到元素:
<div ng-bind-html="customHtml"></div>
然而,AngularJS 會將HTML 渲染為引號內的字串,因為它出於清理目的將其視為不安全。若要解決此問題,您可以使用 $sce 服務或包含 ngSanitize 模組。
使用$sce
首先,將$sce 服務注入控制器:
app.controller('SomeController', function($sce) { // ... });
然後,使用$sce.trustAsHtml() 方法轉換HTML字串轉換為安全格式:
this.customHtml = $sce.trustAsHtml(someHtmlVar);
使用ngSanitize
要使用ngSanitize,首先包含angular-sanitize.min.js 腳本:
<script src="lib/angular/angular-sanitize.min.js"></script>
然後,將ngSanitize 作為依賴項包含在AngularJS中模組:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])
this.customHtml = someHtmlVar;
以上是如何在 AngularJS 視圖中安全地渲染 HTML 片段?的詳細內容。更多資訊請關注PHP中文網其他相關文章!