我的应用中的点击功能不适用于 angular js 中动态创建的元素。
这是我的代码:
HTML代码
<div ng-app="myApp" ng-controller="myCtl">
<p>
Click is not working in table
</p>
<table border="1">
<tr ng-repeat="value in person.records">
<td>{{value.firstname}}</td>
<td>{{value.age}}</td>
<td ng-bind-html="value.button"></td>
</tr>
</table><br />
<br />
<p>
When I click on Click button, My function should be call like below
</p>
<button class="btn btn-primary" type="button" ng-click="trailClick()">Click</button>
</div>
JS代码:在表格中,当我点击&#34;点击按钮&#34;时,我没有得到我想要的功能。
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtl", function($scope, $sce) {
$scope.trailClick = function() {
alert('Clicked ');
}
$scope.person = {
"records": [{
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
}, {
firstname: "Dev",
lastname: "Raj",
age: 50,
eyecolor: "black"
}]
};
var cln_btn = '<button class="btn btn-primary" type="button" ng-click="trailClick()">Click</button>';
for (var x = 0; x < $scope.person.records.length; x++) {
$scope.person.records[x].button = $sce.trustAsHtml(cln_btn);
}
});
答案 0 :(得分:0)
您可以在stackoverflow上找到有关此问题的大量信息。
简而言之,您可以创建自己的指令或安装this one
angular-bind-html-compile
将其作为依赖项包含在您的应用程序中:
angular-bind-html-compile
并将其命名为
bind-html-compile
代码就像:
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<script data-require="ngSanitize@1.3.15" data-semver="1.3.15" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-sanitize.js"></script>
<script src="angular-bind-html-compile.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
var app = angular.module("myApp", ['ngSanitize', 'angular-bind-html-compile']);
app.controller("myCtl", function($scope, $sce, $compile) {
$scope.trailClick = function() {
alert('Clicked ');
}
$scope.person = {
"records": [{
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
}, {
firstname: "Dev",
lastname: "Raj",
age: 50,
eyecolor: "black"
}]
};
var cln_btn = '<button class="btn btn-primary" type="button" ng-click="trailClick()">Click</button>';
for (var x = 0; x < $scope.person.records.length; x++) {
$scope.person.records[x].button = $sce.trustAsHtml(cln_btn);
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtl">
<p>
Click is not working in table
</p>
<table border="1">
<tbody>
<tr ng-repeat="value in person.records">
<td>{{value.firstname}}</td>
<td>{{value.age}}</td>
<td bind-html-compile="value.button"></td>
</tr>
</tbody>
</table>
<br />
<br />
<p>
When I click on Click button, My function should be call like below
</p>
<button class="btn btn-primary" type="button" ng-click="trailClick()">Click</button>
</div>
</body>
</html>
我创建了plunker