使用 ng-bind-html 呈现的 HTML 中触发事件



在这个 plunk 中,我在一个变量中有一个 HTML 表。我用ng-bind-html渲染表格,效果很好。问题是单击单元格时我无法触发事件。例如,单元级别的ng-click不会调用在 AngularJS 中声明的函数。如何捕获点击?

.HTML

<div ng-bind-html="html"></div>

爪哇语

var app = angular.module('app', []);
app.controller('ctl', function ($scope,$sce) {
var htmlTable = `
<table border="1">
<tr>
<td ng-click="clicked()">
$39,431.67
</td>
<td ng-click="clicked()">
$14,861.50
</td>
<td ng-click="clicked()">
$7,848.97
</td>
<td ng-click="clicked()">
$16,721.20
</td>
</tr>
</table> `;
$scope.html = $sce.trustAsHtml(htmlTable);
$scope.clicked = function(){
alert("cell was clicked"); 
};   
});

你需要创建一个directive with compile来完成这项工作,看看这个答案

.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};

最新更新