YoroDiallo YoroDiallo - 2 months ago 7
AngularJS Question

tr index by clicking td in angularjs without jquery

I have a table, when I click I need to return this td name and row index. But if I make this like

ng-click="showIndex(field.name, $index)"
it return index of td, not tr (It's logical I know:) ). I find some way to check parent index, but It's jquery, perhaps there is a way to check it in angular? I have some example

Answer

You should use $parent.$index instead of $index in

<tr ng-repeat='row in table.row'>
    <td ng-click="showIndex(field.name, $parent.$index)" ng-repeat='field in row.fields'>{{field.name}}</td>
</tr>

var app = angular.module('App', []);

app.controller('Ctrl', function($scope) {
  $scope.table = {
row: [{
  fields: [{
    title: "Your name",
    name: "John",
    id: 'name'
  }, {
    title: "Your second name",
    name: "Doe",
    id: 'secondName'
  }, {
    title: "Your age",
    name: 26,
    id: 'age'
  }, {
    title: "Your sex",
    name: "Male",
    id: 'sex'
  }]
}, {
  fields: [{
    title: "Your name",
    name: "Kevin",
    id: 'name'
  }, {
    title: "Your second name",
    name: "Parker",
    id: 'secondName'
  }, {
    title: "Your age",
    name: 32,
    id: 'age'
  }, {
    title: "Your sex",
    name: "Male",
    id: 'sex'
  }]
}, {
  fields: [{
    title: "Your name",
    name: "Barbara",
    id: 'name'
  }, {
    title: "Your second name",
    name: "Streisand",
    id: 'secondName'
  }, {
    title: "Your age",
    name: 60,
    id: 'age'
  }, {
    title: "Your sex",
    name: "Female",
    id: 'sex'
  }]
}, {
  fields: [{
    title: "Your name",
    name: "Linda",
    id: 'name'
  }, {
    title: "Your second name",
    name: "Lorry",
    id: 'secondName'
  }, {
    title: "Your age",
    name: 20,
    id: 'age'
  }, {
    title: "Your sex",
    name: "Female",
    id: 'sex'
  }]
}]
  };

  $scope.showIndex = function(name, index) {
$scope.showResult = name + ' in the row number ' + index;
  }
});
<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="style.css">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src='script.js'></script>
</head>
<body ng-controller="Ctrl">

	<table>
		<thead>
			<tr>
				<th ng-repeat='header in table.row[0].fields'>{{header.title}}</th>
			</tr>
		</thead>

		<tbody>
			<tr ng-repeat='row in table.row'>
				<td ng-click="showIndex(field.name, $parent.$index)" ng-repeat='field in row.fields'>{{field.name}}</td>
			</tr>
		</tbody>
	</table>

  <br>
  <b>{{showResult}}</b>
	</body>
</html>