How to create button dynamically with click event in Angular ?
The task is to create a button dynamically with click event using angular. In these examples when someone clicks on the button then a new button gets created.
The easiest way to create a button in AngularJS is to use the ng-repeat directive. We can easily hook up a repeat logic inside a button click event.
Syntax:
<element ng-repeat="variable in expression"> Contents... </element>
Example: Here we have a counter variable that keeps the count of buttons currently present in the DOM. it gets increased by one each time the main button (GFG) is pressed. the increased count results in a new button generated by ng-repeat.
<!DOCTYPE html> <html ng-app="myApp"> <head> <script src= </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> |
Output: As we keep on clicking the button, the number of buttons keep on increasing in the DOM:


Recommended Posts:
- How to call PHP function on the click of a Button ?
- How to load notification alert on top right corner without click of button in bootstrap ?
- How to create an image element dynamically using JavaScript ?
- What is the use of a double-click event in AngularJs?
- How to change the font of HTML5 Canvas using a button in Angular.js?
- How to add active class on click event in custom list group in Bootstrap 4 ?
- How to create directory with HTML button and PHP ?
- How to create an HTML button that acts like a link?
- Routing in Angular JS using Angular UI Router
- Angular CLI | Angular Project Setup
- button tag vs input type="button" attribute
- How to dynamically load JS inside JS ?
- Dynamically generating a QR code using PHP
- How to dynamically get the content width of a div using AngularJS ?
- How to dynamically change the title of web page using JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



