这是我在 Stackoverflow 上的第一个问题,所以请原谅我犯的任何错误。 我试图在 View 中显示模板中的一些 HTML,我在以下指令中使用了这些 HTML:
app.directive('picturegallery', function () {
return {
scope: true,
restrict: "E",
templateUrl: '../../Controllers/pictureGallery.html'
}
});
我通过应用 .push
在点击时执行此操作, 所以 <picturegallery></picturegallery>
被添加到 $scope.sections
:
app.directive("picgallery", function ($compile) {
return function (scope, element, attrs) {
element.bind("click", function () {
scope.count++;
scope.sections.push({ desc: "<picturegallery></picturegallery>" });
angular.element(document.getElementById('template-id')).append($compile("<picturegallery></picturegallery>")(scope));
});
};
});
我使用 $sce.parseAsHtml
如下所示,它可以工作,但是 HTML 仍然没有转换为模板指向的实际 HTML,只是显示为 <picturegallery></picturegallery>
.我想要 pictureGallery.html
指向的实际模板出现。
$scope.sections = [
{ desc: '<div>hello</div>' },
{ desc: '$sce.parseAsHtml("<picturegallery></picturegallery>")' }
];
有什么方法可以显示模板中的实际内容吗?
我已经经历过几个解决方案,例如 Angularjs: preview sanitized html在 Stackoverflow 上建议使用 $sce.parseAsHtml
和 $sce.trustAsHtml
但它们不适用于我的代码。
最佳答案
对我来说遇到类似问题的最佳解决方案是创建一个自定义过滤器,它允许我呈现导入的 HTML。
app.filter('unsafe', ['$sce', function($sce) { return $sce.trustAsHtml; }])
在我看来,我可以使用过滤器显示 HTML:
<div>{{myCtrl.someHTML | unsafe}}</div>
如果开箱即用,您还需要像这样在 Angular 配置中设置资源白名单:
$sceDelegateProvider.resourceUrlWhitelist(['self', 'https://www.google.com/maps/embed/v1/**']);
(谷歌链接只是为了证明您可以从另一个网站/服务导入外部 HTML 并将其呈现为可信来源)
关于javascript - 将 HTML(用户定义的指令)插入 View - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31987646/