Upon further reflection:
$index
is in relation to the current element within the loop. Considering that you are sorting the array, it's important to store a reference to the object itself from the directive (You can utilize person.id
, for instance, if there's a unique id
for each person).
You have the option to save a reference to the selected individual using ngValue
angular.module('app', []).controller('ctrl', function($scope) {
$scope.selected = { person: null };
$scope.persons = [{id: 1, name: "person1"}, {id: 2, name: "person2"}, {id: 3, name: "person3"}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
<tr class="restTable" data-ng-repeat="person in persons|orderBy:'name'">
<td> {{ person.name}}</td>
<td> <input type="radio" name="radio" ng-model="selected.person" ng-value="person"/></td>
</tr>
</table>
<hr>
<p>Selected Person:</p>
<pre ng-bind="selected.person | json"></pre>
</div>
By incorporating ngValue
and storing a reference to the chosen object during the loop, I am unconcerned with the current position of the object because angularjs ensures that the selected person will be accessible in the controller via $scope.selected.person
.
If you wish to pre-select a person, replace
$scope.selected = { person: null };
With
$scope.selected = { person: $scope.persons[1] };
Remember to define $scope.persons
beforehand! Place this line after declaring the array in your controller. For example:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.persons = [{id: 1, name: "3person1"}, {id: 2, name: "1person2"}, {id: 3, name: "4person3"}];
$scope.selected = { person: $scope.persons[1] };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
<tr class="restTable" data-ng-repeat="person in persons|orderBy:'name'">
<td> {{ person.name}}</td>
<td> <input type="radio" name="radio" ng-model="selected.person" ng-value="person"/></td>
</tr>
</table>
<hr>
<p>Selected Person:</p>
<pre ng-bind="selected.person | json"></pre>
</div>