$ sce.trustAsHtml内渲染指令 [英] Rendering directives within $sce.trustAsHtml
问题描述
我已经包含这里Plunker:<一href=\"http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=$p$pview\">http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=$p$pview
我想一个按钮添加到DOM,并点击应该执行绑定到它的功能时。在这种情况下,应提醒测试。这里是code。
控制器
app.controller('MainCtrl',函数($范围,$ SCE){
$ scope.trustedHtml = $ sce.trustAsHtml('&LT;按钮NG点击=的testAlert()&GT;提交&LT; /按钮&GT;'); $ scope.testAlert =功能(){
警报('测试')
};
});
HTML
&LT;机身NG控制器=MainCtrl&GT;
&LT; DIV NG绑定-HTML =trustedHtml&GT;&LT; / DIV&GT;
&LT; /身体GT;
$ sce.trustAsHtml
和 NG-绑定-HTML
不是为了建立与指令HTML。这种技术是行不通的。
这是因为角度的作品先编译,然后链接。请参阅概念性概述一个很好的解释。
在总之,通过您链接中定义的HTML的时候你的 trustAsHtml
,这是为时已晚角度来编译(并因此理解)的 NG-点击
指令。
为了动态地添加HTML,你应该看 $编译
服务(和/或指令)。 文档是在这里。
I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview
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.
controller
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
and ng-bind-html
are not meant to build HTML with directives. This technique will not work.
This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.
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.
In order to dynamically add HTML, you should be looking at the $compile
service (and/or directives). Docs are here.
这篇关于$ sce.trustAsHtml内渲染指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!