javascript - AngularJS动态加载的元素,里面的ng-click无法触发?
本文介绍了javascript - AngularJS动态加载的元素,里面的ng-click无法触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
在项目中,服务端返回了一个html字符串,写了一个filter,通过$sce.trustAsHtml(text)将字符串编译成可加载的html,但是元素里的ng-click事件无法触发,求解!!
//字符串转html标签过滤器
app.filter("htmlContent",["$sce",function($sce){
return function(text){
return $sce.trustAsHtml(text);
}
}]);
//模拟数据
var jsonArr = [{
temp:"<h1 ng-click='showCoverBox()'>测试</h1>"
}];
//点击事件
$scope.showCoverBox = function(){
console.log("测试");
};
//页面通过ng-repeat展示
<li ng-repeat="item in jsonArr">
div ng-bind-html="item.tmp|htmlContent"></div>
</li>
有人说可以在directive中通过$compile服务,编译DOM,实现动态的事件绑定,但是我想要的是不用指令,有没有其他解决方案,求大神指教~
解决方案
这种情况必须用$compile, 你可以写一个directive, 已属性的形式加到div上
angular.module('app', []).directive('compileHtml', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(function () {return scope.$eval(attrs.ngBindHtml);},
function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
<div ng-bind-html="item.tmp|htmlContent" compile-html></div>
这篇关于javascript - AngularJS动态加载的元素,里面的ng-click无法触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文