在项目中,服务端返回了一个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,实现动态的事件绑定,但是我想要的是不用指令,有没有其他解决方案,求大神指教~
1 回答
喵喔喔
TA贡献1735条经验 获得超5个赞
这种情况必须用$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>
添加回答
举报
0/150
提交
取消