Add or Remove Table Rows Dynamically in AngularJS

← PrevNext →

Using AngularJS ng-repeat directive, you can easily bind JSON array data to an HTML table. You can use the same table to do some simple CRUD operations, like adding or removing data. Here in this post I’ll show you how to add or remove rows of a table dynamically in AngularJS.

Add or Remove Table Rows Dynamically in AngularJS

See this demo

-----------------

If you are new to AngularJS, then I recommend you to read my first article that I have written for beginners.

AngularJS Tutorial for Beginners – My First AngularJS App “Hello World”

-----------------

The Model

Let us first create our model. I have a table, bound to a JSON array, using ng-repeat directive. In my controller section, I’ll assign the JSON array to the ng-repeat directive. This will populate the table with some data initially.

I also have two textboxes to add new values and row to the table. In-addition, I have two buttons to add new row and remove selected rows.

👉 Convert JSON data dyanamically to an HTML table using plain JavaScript
JSON to Table using JavaScript

Please don’t get overwhelmed by the size the of markup. Simply copy the above markup and paste it in your web page, as it is.

Since I have table on my web page, a little styling (using CSS) is necessary to make decent table format.

See the ng-repeat directive usage in <table>. How I am using an array to populate data to the table. The last column in the <table> has checkboxes for each row. I want my users to select the check boxes first, before removing the rows.

Next, I have two buttons, submit (to submit the data) and remove rows (to remove selected rows).

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <style>
        div{
            width:450px;
        }
        ul {
            padding:0;
            margin:2px 5px; 
            list-style:none; 
            border:0; 
            float:left; 
            width:100%;
        }
        li {
            width:50%; 
            float:left; 
            display:inline-block; 
        }
        table, input {
            text-align:left;
        }
        table, td, th 
        {
            margin:10px 0;
            padding:2px 10px;
        }
        td, th {
            border:solid 1px #CCC;
        }
        button {
            padding:3px 5px;
        }
    </style>
</head>
<body>
    <div ng-app="myApp" ng-controller="myController">
        <ul>
            <li>Movie Name</li>
            <li><input type="text" ng-model="name" /></li>
        </ul>
        <ul>
            <li>Name of Director</li>
            <li><input type="text" ng-model="director" /></li>
        </ul>
        <ul>
            <li> </li><li><button ng-click="addRow()"> Add Row </button></li>
        </ul>

        <!--CREATE A TABLE-->
        <table> 
            <tr>
                <th>Code</th>
                    <th>Movie Name</th>
                        <th>Director</th>
            </tr>

            <tr ng-repeat="movies in movieArray">
                <td><label>{{$index + 1}}</label></td>
                <td><label>{{movies.name}}</label></td>
                <td><label>{{movies.director}}</label></td>
                <td><input type="checkbox" ng-model="movies.Remove"/></td>
            </tr>
        </table>

        <div>
            <button ng-click="submit()">Submit Data</button>   
                <button ng-click="removeRow()">Remove Row</button>
        </div>

        <div id="display" style="padding:10px 0;">{{display}}</div>
    </div>
</body>

<!--The Controller-->
<script>
    var app = angular.module('myApp', []);
    app.controller('myController', function ($scope) {

        // JSON ARRAY TO POPULATE TABLE.
        $scope.movieArray =
        [
            { 'name': 'Total Eclipse', 'director': 'Agniezka Hollan' },
            { 'name': 'My Left Foot', 'director': 'Jim Sheridan' },
            { 'name': 'Forest Gump', 'director': 'Robert Zemeckis' }
        ];

        // GET VALUES FROM INPUT BOXES AND ADD A NEW ROW TO THE TABLE.
        $scope.addRow = function () {
            if ($scope.name != undefined && $scope.director != undefined) {
                var movie = [];
                movie.name = $scope.name;
                movie.director = $scope.director;

                $scope.movieArray.push(movie);

                // CLEAR TEXTBOX.
                $scope.name = null;
                $scope.director = null;
            }
        };

        // Remove selected rows from table.
        $scope.removeRow = function () {
            var arrMovie = [];
            angular.forEach($scope.movieArray, function (value) {
                if (!value.Remove) {
                    arrMovie.push(value);
                }
            });
            $scope.movieArray = arrMovie;
        };

        // Finally, submit the data.
        $scope.submit = function () {
            var arrMovie = [];
            angular.forEach($scope.movieArray, function (value) {
                arrMovie.push('Name:' + value.name + ', Director:' + value.director);
            });
            $scope.display = arrMovie;
        };
    });
</script>
</html>
Try it

In the above script (controller), I have three functions, named as addRow, removeRow and submit.

The addRow() function is called when user clicks a button after entering the values in the textboxes. Calling a function in AngularJS controller is very simple. I am using the ng-click directive to call the function. The function has an array to collect data from textboxes and push the values inside the JSON array, which will then update the <table>

In the removeRow() function, I am using forEach() function to loop through each value in the table row. Since the last column has a checkbox attach to each row, it will check if any checkbox is selected. This function will re-create the <table>, minus the checked row index.

angular.forEach($scope.movieArray, function (value) {
    if (!value.Remove) {
        arrMovie.push(value);
    }
});

👉 Create a simple CRUD application in Angular with Web API
CRUD application in Angular

The value.Remove will return a Boolean true (for checked) or false.

Finally, I got the submit function in my controller. This is optional (based on the title of this post). Once you are ready with new data (either you have added new rows to the table or removed previous values from table), you can submit the tables data. Save the data to a database using Web API method

See this demo

Well that’s it. Thanks for reading.

← PreviousNext →