Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 712
alexeevyci Avatar asked Dec 28 '15 18:12

alexeevyci


2 Answers

Issue is with this line of code:

$compile(generated)($scope);

Instead it should be:

$compile(generated.contents())($scope);
like image 199
Gaurav Avatar answered Oct 31 '22 21:10

Gaurav


You can assign the function to a scope variable and depending on your business logic assign appropriate functions to your ng-click. In the below example $scope.addGeoFence() is added to the ng-click of "Add GeoFence" list-item

$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>
like image 29
Sidharth Middela Avatar answered Oct 31 '22 21:10

Sidharth Middela