如何动态添加 ng-click 处理程序 [英] How to add ng-click handler dynamically
问题描述
我尝试在之前生成的按钮上添加 ng-click(动态),但效果不佳.此外,我已经尝试了在此论坛上找到的所有解决方案,但没有一个效果很好.
我的 html 代码:
<div class="container max_height" ng-controller="myCtrl"><div id="play" tabindex="0" ng-init="init()" ng-keydown="keyDown($event)">{{ 内容 }}
<script src="js/angular.min.js"></script><script src="js/script.js"></script>
我的 AngularJS 代码:
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 生成 = element.html(el);$compile(生成)($scope);}$scope.startAnimation = function(){console.log("点击");}});
我的错误是RangeError: Maximum call stack size exceeded",这是由 $compile(generated)($scope); 生成的;.从第一个衍生而来的另一个问题是,如果我单击按钮,则函数 startAnimation 将执行数百次.
请给我一个解决方案.错在哪里.
问题在于这行代码:
$compile(generated)($scope);
应该是:
$compile(generated.contents())($scope);
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.
My html code:
<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>
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");
}
});
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.
Issue is with this line of code:
$compile(generated)($scope);
Instead it should be:
$compile(generated.contents())($scope);
这篇关于如何动态添加 ng-click 处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!