在 $sce.trustAsHtml 中呈现指令 [英] Rendering directives within $sce.trustAsHtml
问题描述
我在此处包含了一个 Plunker:http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=预览
I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview
我正在尝试向 DOM 添加一个按钮,单击时应执行绑定到它的函数.在这种情况下,它应该提醒测试".这是代码.
I'm trying to add a button to the DOM and when clicked should execute the function bound to it. In this case it should alert "testing". Here is the code.
控制器
app.controller('MainCtrl', function($scope, $sce) {
$scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');
$scope.testAlert = function () {
alert('testing')
};
});
HTML
<body ng-controller="MainCtrl">
<div ng-bind-html="trustedHtml"></div>
</body>
推荐答案
$sce.trustAsHtml
和 ng-bind-html
并不是为了使用指令构建 HTML.这种技术行不通.
$sce.trustAsHtml
and ng-bind-html
are not meant to build HTML with directives. This technique will not work.
这是因为 angular 的工作原理是先编译然后链接.请参阅概念概述以获得很好的解释.
This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.
简而言之,当您链接 trustAsHtml
中定义的 HTML 时,Angular 编译(并因此理解)ng-click
指令为时已晚.
In short, by the time you link the HTML defined in your trustAsHtml
, it is too late for angular to compile (and therefore understand) the ng-click
directive.
为了动态添加 HTML,您应该查看 $compile
服务(和/或指令).文档在这里.
In order to dynamically add HTML, you should be looking at the $compile
service (and/or directives). Docs are here.
这篇关于在 $sce.trustAsHtml 中呈现指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!