Reputation: 525
I would like to get the values of a selected row from a table.This is what i tried so far and the attached plunkr. https://plnkr.co/edit/QDPh4q0hQdlW09orayyL?p=preview
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' +
document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]"src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr ng-click="getData()">
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
Upvotes: 1
Views: 6237
Reputation: 600
angular.module("MyApp",[])
.controller("MyCtrl", function($scope){
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<table border="1">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</tbody>
</table>
</div>
</div>
Upvotes: 2
Reputation: 13498
It is better to iterate each person
via ng-repeat
and pass them to your function explicitly instead of hardcoding in HTML and so working with DOM:
$scope.people = [{
name: 'Jill',
lastName: 'Smith',
age: 50
},
....
]
$scope.getData = function(person) {
console.log('Selected person is ' + person.name);
}
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr ng-repeat='person in people' ng-click="getData(person)">
<td>{{person.name}}</td>
<td>{{person.lastName}}</td>
<td>{{person.age}}</td>
</tr>
</table>
Upvotes: 6
Reputation: 31
Try this
$scope.getData=function(event){
console.log(event.target);
}
<tr ng-click="getData($event)">
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
Upvotes: 0