编译 ng-bind-html 后 ng-click 不起作用 [英] ng-click not working after compile ng-bind-html
问题描述
我有一个指令
app.directive("dir", function($compile, $sce){返回{限制:E",链接:功能(范围,元素,属性){scope.$watch('content',function(){var html = $sce.trustAsHtml(attr.content);scope.alabala = $compile(html)(scope);},真的);},模板:<div ng-bind-html='alabala'></div>",}});
控制器:
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);});};}
在我的索引页上,我有:
<dir id="dir" ></dir>
我的自定义服务每次返回包含例如的不同 html
我想要做的是每次当我在指令的内容中推送不同的值以编译它并将其放入我的 html 并处理来自我的控制器的点击功能时.因为我是 AngularJS 的新手,所以我一直在努力解决这个问题.请帮忙.
你不需要处理 $sce 来满足您的目的.
您可以将 HTML
作为字符串传递给指令.在指令中编译后它会工作.
在 HTML
中需要 指令
在 myVal
控制器中设置不同的值
$scope.myVal = '<button ng-click=\'buttonClick()\'>I\'m button</button>';//HTML 作为字符串
指令
myApp.directive('dir', function($compile, $parse) {返回 {限制:'E',链接:函数(范围,元素,属性){scope.$watch(attr.content, function() {element.html($parse(attr.content)(scope));$compile(element.contents())(scope);}, 真的);}}})
查看演示
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
<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.
You don't need to deal with $sce to meet your purpose.
You can pass your HTML
as string to the directive. After compilation in the directive it'll work.
In HTML
where you need the directive
<dir id="dir" content="myVal"></dir>
Set different value in myVal
your controller
$scope.myVal = '<button ng-click=\'buttonClick()\'>I\'m button</button>'; // HTML as string
The 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
这篇关于编译 ng-bind-html 后 ng-click 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!