我有这样的 html 模板:
我想使用“ng-bind-html”绑定(bind)此模板,如下所示:
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$compile',
function($scope, $compile) {
var templateHTML =
'I am an <code>HTML</code>string with ' +
'<span class="pointer"><i class="icon-refresh pointer" ng-click="refresh()"></i></span>';
$scope.myHTML = $compile(templateHTML)($scope);
}
]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-sanitize.js"></script>
<div ng-app="bindHtmlExample">
<div ng-controller="ExampleController">
<p ng-bind-html-unsafe="myHTML"></p>
<p ng-bind-html="myHTML"></p>
</div>
</div>
我什么也没得到。 如何解决这个问题。
最佳答案
我认为这里可能的解决方案是编写自己的指令,例如
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$compile', function ($scope, $compile) {
var templateHTML =
'<div>I am an <code>HTML</code>string with ' +
'<span class="pointer"><i class="icon-refresh pointer" ng-click="refresh()">i</i></span></div>';
$scope.myHTML = templateHTML;
$scope.refresh = function () {
console.log('refresh')
};
}]);
angular.module('bindHtmlExample').directive('myHtml', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function link($scope, $element, attrs) {
attrs.$observe('myHtml', function (value) {
var $el = $compile(value)($scope);
$element.empty().append($el)
})
}
}
}])
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-sanitize.js"></script>
<div ng-app="bindHtmlExample">
<div ng-controller="ExampleController">
<p ng-bind-html-unsafe="myHTML"></p>
<p ng-bind-html="myHTML"></p>
<p my-html="{{myHTML}}"></p>
</div>
</div>
关于javascript - 在 Angularjs 中使用 ng-bind-html 不显示 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112365/