Wednesday 15 April 2015

Add or remove data in html table using AngularJS

Today I am working on generating json data into a table and suddenly I thought of why not make it more dynamic, so that I can add row or remove row runtime. So then I came up with two javascript array functions push and splice which help me work out my idea. So I first used ng-repeat to populate the html table and just added one more column in the table which consists of a "remove" link which removes the row it consists of and a text field and a button to add the text value into the table. It's so dynamic, page is never reloaded, no tension of losing sessions. Just go through this tutorial and do comment if you have any questions.

<html ng-app="app">
<head>
<title>
    Add to remove from rows from table.
</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript">
    app = angular.module('app',[]);
    app.controller('MyCtrl',function($scope) {
        $scope.myData = [];
        $scope.addData = function() {
            $scope.myData.push($scope.inData);
            $scope.inData="";
        }
        $scope.removeData = function(selData) {
            $scope.myData.splice($scope.myData.indexOf(selData),1);
        }
    });
</script>
</head>
<body ng-controller="MyCtrl">
<label>Enter data to add : </label>
<input type="text" name="inData" ng-model="inData" />
<input type="button" ng-click="addData()" value="Add Data" />
<table border="1">
    <tr>
        <th>Added Data</th>
    </tr>
    <tr ng-repeat="data in myData" >
        <td>{{data}}</td>
        <td><a href="" ng-click="removeData(data)">Remove</a></td>
    </tr>
</table>
</body>
</html>

 


Added Data
{{data}}Remove

No comments: