【发布时间】:2015-11-20 17:48:09
【问题描述】:
我正在尝试使用 Angular.js 实现基于 Web 的表格,以便可以使用单选按钮选择每一行。行可以向上或向下交换,并且选择状态应与行一起交换。到目前为止,可以添加新行,行交换工作正常,并且选定行索引的范围变量会在用户单击单选按钮时更新。
我遇到的问题是单选按钮的选中状态和范围变量不同步。更具体地说,虽然范围变量在行交换期间正确更新,但单选按钮通常在交换后取消选择。也可能发生所选单选按钮与范围变量中的索引不同的情况。
欢迎任何有关如何解决此问题的建议!
到目前为止我已经实现的 JSFiddle 可以在这里找到:
http://jsfiddle.net/7jeume9r/38/
HTML 代码
<div ng-controller="SelectTableController">
<table id="select-table">
<thead>
<tr>
<th> Text </th>
<th> Select? </th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in entries">
<td> {{x['text']}} (id: {{$index}}) </td>
<td> <input type="radio" ng-model="$parent.selectedchoice" name="selectedchoice" value="{{$index}}"/> </td>
<td>
<button type="button" ng-click="moveUpEntry(x)" ng-show="$index > 0"> Move up </button>
<button type="button" ng-click="moveDownEntry(x)" ng-show="$index < entries.length-1"> Move down </button>
</td>
</tr>
</tbody>
</table>
<div>
<input type="text" ng-model="newtext"> </input>
<button type="button" ng-click="addEntry()"> Add </button>
</div>
<div> <tt> Selected Choice: {{selectedchoice}} </tt> </div>
</div>
Javascript / Angular.js 代码
angular.module('DemoApp', []).controller('SelectTableController', function($scope) {
$scope.entries = [{text:"abc"}, {text:"def"}]
$scope.selectedchoice = '-1'
$scope.addEntry = function() {
var text = $scope.newtext
$scope.entries.push({text: text})
$scope.newtext = ""
}
$scope.moveUpEntry = function(entry) {
var index = $scope.entries.indexOf(entry)
if (index > 0 && index < $scope.entries.length) {
$scope.entries.swap(index,index-1)
if ($scope.selectedchoice == index)
$scope.selectedchoice = index-1
else if ($scope.selectedchoice == index-1)
$scope.selectedchoice = index
}
}
$scope.moveDownEntry = function(entry) {
var index = $scope.entries.indexOf(entry)
if (index >= 0 && index < $scope.entries.length-1) {
$scope.entries.swap(index,index+1)
if ($scope.selectedchoice == index)
$scope.selectedchoice = index+1
else if ($scope.selectedchoice == index+1)
$scope.selectedchoice = index
}
}
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
});
【问题讨论】:
标签: javascript html angularjs