How to add ng-click handler dynamically

一个人想着一个人 提交于 2019-12-06 02:33:16

问题


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.


回答1:


Issue is with this line of code:

$compile(generated)($scope);

Instead it should be:

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



回答2:


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>


来源:https://stackoverflow.com/questions/34498558/how-to-add-ng-click-handler-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!