How to add ng-click handler dynamically

I tried adding ng-click to the button generated earlier (dynamic) but it doesn’t work. I have also tried all the solutions found in this forum, and no one works well.

My html code is:

<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 mistake: “RangeError: maximum call stack size exceeded”, and this is generated by compiling $ (generated) ($ scope) ;, Another problem arising from the first is that if I make one click on the button, then the startAnimation function will be executed hundreds of times.

Please give me a solution. Where is the mistake.

+4
source share
2 answers

The problem with this line of code:

$compile(generated)($scope);

:

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

- ng-. $scope.addGeoFence() ng- " GeoFence"

$scope.layout = [
      {name: 'Home', icon: 'home'},
      {name: 'Add Geofence', 
       icon: 'add_location', 
       click: $scope.addGeoFence}
];

$scope.addGeoFence = function() {
    console.log("calling addGeoFence()");
}

<md-list>
    <md-list-item ng-repeat="snav in layout">
        <md-button class="md-raised" ng-click="(snav.click)()" flex>
            <md-icon md-font-library="material-icons">{{snav.icon}}
            </md-icon>
            <span>{{snav.name}}</span>
        </md-button>
    </md-list-item>
</md-list>
+1

Source: https://habr.com/ru/post/1621996/


All Articles