单击动态元素

Fire ng-click on dynamic element

本文关键字:元素 动态 单击      更新时间:2023-09-26

我想用可以触发ng-click事件来创建动态元素,并想用DataTables来实现这一点,在DataTables中,行是通过AJAX获得的,并且是动态创建的。问题是,ng-click没有在这些行元素上激发。我在JSBin中用另一种情况重新创建了这个问题(DataTables部分实际上并不重要(。

Html

<div id="elements" ng-controller="TestController as controller">
  <button ng-click='doSomething()'>This button will work</button>
  </div>
  <button class="click">Create element</button>

单击Create element按钮时,会将一个按钮添加到#elements div中的DOM中。单击div中的按钮,控制台将输出一些内容。当您单击#elementsdiv中已经创建的按钮时,它会执行它必须执行的操作,但不使用动态创建的按钮。

JS

app.controller('TestController', ['$http', '$scope', function ($http, $scope) {
  //The NG function.
  $scope.doSomething = function(){
    console.log('Function fired!');
  };
}]);                                
//Create new element in the #elements div.                                  
(function(){
  $(".click").on("click", function(){
    var element = "<button ng-click='doSomething()'>This will not work</button>";
    $("#elements").append(element);
  });
})();

http://jsbin.com/hakibocabe/edit?html,js,控制台,输出

我做错了什么?我是不是错过了什么?

据我所知,您希望在单击另一个按钮时将按钮添加到div中,并让div中的每个按钮使用doSomething函数。

因此,对于一个纯角度的答案,你想要这样的东西:

HTML:

<div ng-controller="TestController">
  <div ng-repeat="button in buttons">
    <button ng-click="doSomething()">Button</button>
  </div>
  <button ng-click="addButton()">Add</button>
</div>

JS:

app.controller('TestController', ['$http', '$scope', function ($http, $scope) {
  $scope.buttons = [];
  $scope.doSomething = function(){
    console.log('Function fired!');
  };
  $scope.addButton = function(){
    $scope.buttons.push($scope.buttons.length)//or whatever content
  };
}]); 

虽然@Radmer van der Heyde的回答很好地解释了如何以Angular的方式将按钮添加到DOM中(我真的很感激(,但@Claies建议我使用Angular DataTables而不是使用普通的jQuery DataTables,并指出了如何以Angular的方式实现这一点。

我已经复习了Angular DataTables,现在正在使用它,这基本上解决了我的问题。因此,如果您遇到与我相同的问题,请使用Angular DataTables:http://l-lin.github.io/angular-datatables/#/welcome

我认为您需要使用$compile服务,正如您在另一个答案中看到的那样:

ng点击无法从动态生成的HTML 中工作

希望它能有所帮助!