如何动态添加点击处理程序 [英] How to add ng-click handler dynamically
问题描述
我试图添加点击在(动态)之前生成的按钮,但是没有奏效。另外我也尝试过在这个论坛上找到的所有解决方案,没有人能很好的工作。
I tried to add ng-click on a button generated before (dynamic), but didn't work well. Also I tried already all solutions found on this forum and no one work well.
我的html代码:
<body class="max_height" ng-app="myApp">
<div class="container max_height" ng-controller="myCtrl">
<div id="play" tabindex="0" ng-init="init()" ng-keydown="keyDown($event)">
{{ content }}
</div>
</div>
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
</body>
我的AngularJS代码:
My AngularJS code:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $compile) {
$scope.init = function() {
var el = '<button class="btn" id="start" data-ng-click="startAnimation()">Start</buttom>';
var element = angular.element(document.querySelector('#play'));
var generated = element.html(el);
$compile(generated)($scope);
}
$scope.startAnimation = function(){
console.log("click");
}
});
我的错误是RangeError:超过最大调用堆栈大小,这是由$ compile(生成的)($范围); 。另一个问题,从第一个派生出来的是,如果我点击按钮,那么函数startAnimation将执行数百次。
My error is "RangeError: Maximum call stack size exceeded" and this is generated by $compile(generated)($scope); . Another problem, derived from the first, is that if I make one click on button then the function startAnimation will me executed hundreds of times.
请给我一个解决方案。
Please give me a solution. Where is the mistake.
推荐答案
问题是这行代码:
$compile(generated)($scope);
相反,应该是:
$compile(generated.contents())($scope);
这篇关于如何动态添加点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!