如何在Angular中用点击事件动态地创建按钮
我们的任务是使用angular动态地创建一个带有点击事件的按钮。在这些例子中,当有人点击按钮时,一个新的按钮会被创建。
在AngularJS中创建一个按钮的最简单方法是使用ng-repeat指令。我们可以很容易地在一个按钮的点击事件中挂上一个重复逻辑。
语法:
<element ng-repeat="variable in expression"> Contents... </element>
例子:这里我们有一个计数器变量,用来保持当前存在于DOM中的按钮的数量。每当主按钮(GFG)被按下时,它就会增加一个。增加的数量会导致ng-repeat生成一个新按钮。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>
</head>
<body ng-controller="MyController">
<center>
<h1 style="color:green">
GeeksforGeeks
</h1>
<button type="button"
ng-click="click(this)">
GFG
</button>
<br>
<!-- Dynamically created
button using repeat -->
<button type="button"
ng-repeat="i in range(0, counter)">
New button!
</button>
</center>
</body>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['scope', function(scope) {
scope.counter = 0;
scope.click = function(scope) {
scope.counter++;
}
$scope.range =
function(min, max, step) {
step = step || 1;
var input = [];
for (var i = min; i < max; i += step) {
input.push(i);
}
return input;
};
}]);
</script>
</html>
输出:随着我们不断地点击按钮,DOM中的按钮数量不断增加。