In this article I will explain with an example, how to get the TD value of the HTML Table row which is populated from JSON array using AngularJS ng-repeat directive.
This article will explain how to get the TD value of the HTML Table when Button within the HTML Table row is clicked using AngularJS.
How to get TD value from Table row using AngularJS in HTML
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML Table which will be populated from JSON array using ng-repeat directive.
Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetDetails function.
Populating the HTML Table
An array of JSON objects is created and assigned to the Customers JSON array.
The ng-repeat directive as the name suggests repeats the element based on the length of the collection, in this scenario it will repeat the TR element (HTML Table Row).
The TBODY element of the HTML Table has been assigned ng-repeat directive in order to iterate through all the items of the Customers JSON array.
For each JSON object in the Customers JSON array, a TR element (HTML Table Row) is generated and appended into the HTML Table.
Getting the Row details of the HTML Table row on Button click
When the Button is clicked, the GetDetails function of the Controller gets called. Inside the GetDetails function, the value of the Row Index of the HTML Table row is fetched as parameter.
This Row Index is used to fetch the details of the HTML Table Row from the JSON array.
Finally the details of the HTML Table row is displayed using JavaScript Alert Message Box.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Customers = [
{ Name: "John Hammond", Country: "United States" },
{ Name: "Mudassar Khan", Country: "India" },
{ Name: "Suzanne Mathews", Country: "France" },
{ Name: "Robert Schidner", Country: "Russia" }
];
$scope.GetDetails = function (index) {
var name = $scope.Customers[index].Name;
var country = $scope.Customers[index].Country;
$window.alert("Name: " + name + "\nCountry: " + country);
};
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<table cellpadding="0" cellspacing="0">
<tr>
<th>Name</th>
<th>Country</th>
<th></th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.Name}}</td>
<td>{{m.Country}}</td>
<td><input type="button" value="Get Details" ng-click="GetDetails($index)" /></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Screenshot
Demo
Downloads