Add or Remove Table Rows Dynamically in AngularJS

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 the 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.

Similar Post: Convert JSON Data Dynamically to HTML Table using JavaScript

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <style>
        div{
            font:15px Verdana;
            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;
            font:13px Verdana;
        }
        table, td, th 
        {
            margin:10px 0;
            padding:2px 10px;
        }
        td, th {
            border:solid 1px #CCC;
        }
        button {
            font:13px Verdana;
            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>

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.

See the Demo

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

The AngularJS 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 ROW(s) 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>

See the Demo

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);
    }
});

Also Read: Add Values from Textboxes to GridView using jQuery

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

Well that’s it. Thanks for reading.

Previous - AngularJS forEach() Function - Loop Through Each Item in An ArrayNext - Implement a Search Filter on an HTML Table



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!