【问题标题】:Updating ngModel of radio buttons in Angular.js更新 Angular.js 中单选按钮的 ngModel
【发布时间】: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


    【解决方案1】:

    您的单选按钮应该是“行”的一部分,并且单选按钮被选中

    checked="checked"
    

    你不能像你一样用价值来检查它们

    <input type="radio" ng-model="$parent.selectedchoice" name="selectedchoice" value="{{$index}}"/>
    

    我正在尝试修复您的 jsFiddle atm。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2013-01-08
      • 2021-04-02
      • 2014-03-21
      • 2017-08-20
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多