我从另一个问题中得到了代码,它很简单而且工作正常
<div ng-controller="ExampleController">
<p ng-bind-html="testHTML"></p>
(function(angular) {
'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.testHTML = 'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}]);
})(window.angular);
假设我要获取一个对象,并且想要显示该对象的元素
var obj = {
title: 'Title',
description: 'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>'
};
$scope.testHTML = obj;
那么我应该如何只绑定html末尾的描述呢?我试着<p ng-bind-html="{{testHTML.description}}"></p>
和<p ng-bind-html="testHTML.description"></p>
尝试使用此代码段绑定HTML
首先,您可以创建自定义过滤器以绑定AngularJS中的HTML。
现在,您只需编写即可在myApp模块的任何位置使用此过滤器,即可yourHTML | html
完成工作。
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope','$sce', function($scope, $sce) {
var obj = {
title: 'Title',
description: 'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>',
description1: 'I am an <b>HTML</b>string with ' +
'<a href="#">links!</a> and other <u><b>stuff</b></u>'
};
$scope.testHTML = obj;
//Use $SCE in controller
var preview_data = obj.description;
$scope.htmlSafe = $sce.trustAsHtml(preview_data);
}]);
//Custom filter (Alternate way)
myApp.filter('html', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text);
};
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="GreetingController">
<b>By using custom filter</b>
<div ng-bind-html="testHTML.description | html"></div>
<div ng-bind-html="testHTML.description1 | html"></div>
<br/>
<b>By using $SCE inside controller</b>
<div ng-bind-html="htmlSafe"></div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句