我本周刚刚开始在AngularJS上进行一个新的项目,而且我不得不尽快的加快速度.
我的一个要求是动态添加html内容,内容可能会有一个点击事件.
所以我下面的代码Angular代码显示一个按钮,当点击它时,它动态地添加另一个按钮.点击动态添加的按钮,应该添加另一个按钮,但是我无法在动态添加的按钮上获得ng点击
< button type =“button”id =“btn1”ng-click =“addButton()”>点击我< / button>
工作代码示例在这里
http://plnkr.co/edit/pTq2THCmXqw4MO3uLyi6?p=preview
var app = angular.module('plunker',[]); app.controller('MainCtrl',function($scope) { $scope.name = 'World'; $scope.addButton = function() { alert("button clicked"); var btnhtml = '<button type="button" ng-click="addButton()">Click Me</button>'; angular.element(document.getElementById('foo')).append((btnhtml)); } });
<!DOCTYPE html> <html ng-app="plunker"> <head> <Meta charset="utf-8" /> <title>AngularJS Plunker</title> <script> document.write('<base href="' + document.location + '" />'); </script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.0.x" src="//code.angularjs.org/1.3.0/angular.js" data-semver="1.3.0"></script> </head> <body ng-controller="MainCtrl"> <p>Hello {{name}}!</p> <div id="foo"> <button type="button" id="btn1" ng-click="addButton()">Click Me </button> </div> </body> </html>
app.controller('MainCtrl',function($scope,$compile) { var btnhtml = '<button type="button" ng-click="addButton()">Click Me</button>'; var temp = $compile(btnhtml)($scope); //Let's say you have element with id 'foo' in which you want to create a button angular.element(document.getElementById('foo')).append(temp); var addButton = function(){ alert('Yes Click working at dynamically added element'); } });
您需要在这里添加$compile服务,这将绑定角指令,如ng-click到您的控制器范围.并且不要忘记在控制器中添加$compile依赖关系,如下所示.
这里是plunker demo