Open In App

How to Create Button Dynamically with Click Event in Angular ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The task is to create a button dynamically with a click event using AngularJS, i.e., whenever 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 by using the ng-click Directive.

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 the ng-repeat directive.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
 
<head>
    <script src=
    </script>
</head>
 
<body ng-controller="MyController">
    <center>
        <h1 style="color:green">
            GeeksforGeeks
        </h1>
        <h3>
            How to create button dynamically
            with click event in AngularJS?
        </h3>
        <button type="button"
                ng-click="click(this)">
            GFG
        </button>
        <br><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 keeps on increasing in the DOM: 



Last Updated : 18 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads