Angularjs 如何使用Angular 1.4注入HTML?
我有一个包含原始HTML字符串数组的数据源。我必须在页面中向用户显示这些内容 对于Angular来说有点新,我尝试的第一件事是:Angularjs 如何使用Angular 1.4注入HTML?,angularjs,Angularjs,我有一个包含原始HTML字符串数组的数据源。我必须在页面中向用户显示这些内容 对于Angular来说有点新,我尝试的第一件事是: <div ng-repeat="html in ctrl.html" ng-bind="html"></div> 这会导致Angular转义我的HTML并将其显示为字符串。这不是我需要的,但至少它表明Angular确实在加载数据 在谷歌搜索中,我读到了ng bind html unsafe指令,我理解该指令应该将文本注入html文档中,而
<div ng-repeat="html in ctrl.html" ng-bind="html"></div>
这会导致Angular转义我的HTML并将其显示为字符串。这不是我需要的,但至少它表明Angular确实在加载数据
在谷歌搜索中,我读到了ng bind html unsafe指令,我理解该指令应该将文本注入html文档中,而不以任何方式进行转义或清理,这正是我想要的,因为我必须信任我们的数据源
<div ng-repeat="html in ctrl.html" ng-bind-html-unsafe="html"></div>
这也不行。它只是给我看了一张空白页。当我打开DocumentInspector时,我看到HTML数组中的每个条目都有一个div标记,但是div都是空的
在GoogleFu上做了更多的工作后,我发现了关于在$scope上调用方法的讨论,以便更好地使用它。他们说ng bind html不安全是不推荐的
关于如何使用Angular的不同版本实现我所需要的功能的各种方法,我都在讨论如何使用今天的版本:1.4?我认为您必须“清理”html
例如:
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
this.html = array with your htmls;
this.sanitizeHtml = function(html) {
return $sce.trustAsHtml(html);
};
}]);
然后
我认为它会起作用
<div ng-repeat="html in ctrl.html" ng-bind-html="ctrl.sanitizeHtml(html)"></div>
这将起作用使用ngSanitize模块
var app = angular.module("myApp", ['ngSanitize']);
尝试将$sce注入控制器,并将$sce.trustAsHtml注入html
myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
var app = angular.module("myApp", ['ngSanitize']);