Monday, August 12, 2019

Add or Remove Table Rows Dynamically in AngularJS


Add or Remove Table Rows Dynamically in AngularJS
The Model
Let us first create our model. I have a table, bound to a JSON array, using ng-repeatdirective. 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.
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{
            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>

<!--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 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>


In the above script (controller), I have three functions, named as addRowremoveRow 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-clickdirective 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);
    }
});

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...