How to add ng-click handler dynamically

alexeevyci picture alexeevyci · Dec 28, 2015 · Viewed 11.2k times · Source

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.

Answer

Gaurav picture Gaurav · Dec 28, 2015

Issue is with this line of code:

$compile(generated)($scope);

Instead it should be:

$compile(generated.contents())($scope);