[英]ng-click not working after compile ng-bind-html
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. 我想要做的是每次当我在我的指令的内容中推送一个不同的值来编译它并将它放在我的html中并从我的控制器处理click函数时。 Because I'm new to AngularJS I have been struggling with this problem for sometime.
因为我是AngularJS的新手,所以我一直在努力解决这个问题。 Please help.
请帮忙。
You don't need to deal with $sce to meet your purpose. 您无需处理$ sce以满足您的目的。
You can pass your HTML
as string to the directive. 您可以将
HTML
作为字符串传递给指令。 After compilation in the directive it'll work. 在指令编译后它将起作用。
In HTML
where you need the directive
在需要
directive
HTML
中
<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);
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.