javascript 编译 ng-bind-html 后 ng-click 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21370080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-click not working after compile ng-bind-html
提问by user1
I have a directive
我有一个指令
app.directive("dir", function($compile, $sce){
return{
restrict: "E",
link: function(scope, element, attr){
scope.$watch('content',function(){
var html = $sce.trustAsHtml(attr.content);
scope.alabala = $compile(html)(scope);
},true);
},
template: "<div ng-bind-html='alabala'></div>",
}
});
a controller:
控制器:
function MainController($scope, $http, customService, $location, $sce, $compile){
$scope.init = function(){
customService.get().success(function(data) {
var html = $sce.trustAsHtml(data);
$("#dir").attr("content", data);
});
};
}
and on my index page I have:
在我的索引页面上,我有:
<div id="div" ng-controller="MainController" class="pull-right span3" ng-init="init()">
<dir id="dir" ></dir>
</div>
my custom service returns every time a different html containing for example
我的自定义服务每次包含不同的 html 时返回,例如
<button ng-click='click()'>Click me</button>
What I am trying to do is every time when I push a different value in the content of my directive to compile it and put it in my html and handle the click function from my controller. Because I'm new to AngularJS I have been struggling with this problem for sometime. Please help.
我想要做的是每次当我在指令的内容中推送不同的值以编译它并将其放入我的 html 并处理来自我的控制器的点击功能时。因为我是 AngularJS 的新手,所以我一直在为这个问题苦苦挣扎。请帮忙。
回答by Tasnim Reza
You don't need to deal with $sceto meet your purpose.
您不需要处理$sce来满足您的目的。
You can pass your HTML
as string to the directive. After compilation in the directive it'll work.
您可以将HTML
as 字符串传递给指令。在指令中编译后,它将起作用。
In HTML
where you need the directive
在HTML
你需要的地方directive
<dir id="dir" content="myVal"></dir>
Set different value in myVal
your controller
在myVal
控制器中设置不同的值
$scope.myVal = '<button ng-click=\'buttonClick()\'>I\'m button</button>'; // HTML as string
The directive
这 directive
myApp.directive('dir', function($compile, $parse) {
return {
restrict: 'E',
link: function(scope, element, attr) {
scope.$watch(attr.content, function() {
element.html($parse(attr.content)(scope));
$compile(element.contents())(scope);
}, true);
}
}
})
Check the Demo
检查 Demo