正如我在評論中寫道:
$index
是在循環相對到當前元素因爲你排數組,那麼你需要保存從指令中引用對象本身(例如,您可以使用person.id
(如果每個人都有唯一的id
)。
您可以通過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>
這裏我使用的ngValue
並保存到循環內的選擇對象的引用保存到所選的人蔘考。我不關心對象的當前位置,因爲angularjs通過$scope.selected.person
確保所選人員可以在控制器中使用。
如果您要預先選擇一個人,更換
$scope.selected = { person: null };
隨着
$scope.selected = { person: $scope.persons[1] };
但是不要忘了之前聲明$scope.persons
!在之後放置該行,在控制器中聲明該數組。例如:
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>
'$ index'是相對於至**當前元素在環**並且由於要排序的陣列則需要保存對象本身上的參考(例如,你可以使用'person.id'(如果你對每個人都有一個唯一的'id') –
這個想法一旦被選擇通過'persons [$ scope.selectedPerson]來訪問它, – AlexP