如何将单选按钮组重置为特定值

时间:2015-04-11 17:33:06

标签: javascript html angularjs

我有一组单选按钮,我正在使用ng-repeat来显示。我默认选择了最后一个单选按钮(ng-checked =“$ last”):

Status: <span ng-repeat="button in statusList">
    <input type="radio" name="status" ng-model="selectedStatus" value="{{button.value}}" ng-checked="$last"/>{{button.name}}</span>

我的“statusList”如下:

$scope.statusList = [
   {"name": "Active", "value": "active"},
   {"name": "Inactive", "value": "inactive"},
   {"name": "Either", "value": "either"}
];

它按原样运行,但是,我还希望有一个重置/清除表单按钮,无论用户选择了什么,都会再次选择最后一个单选按钮,我无法让Angular这样做。我到目前为止看到的代码示例只是取消选中所有单选按钮而不是返回默认的$ last。我的清晰表格方法如下(删除表格中的其他元素):

$scope.clearSearchData = function() {
    $scope.selectedStatus = "either";
    $scope.MyForm.$setPristine();
};

我第一次按下清除按钮时,上面的代码可以将所选按钮重置为最后一个(或者如果我硬编码不同的值,则可以使用另一个单选按钮),但后续时间无效,保留用户的任何按钮最后按下仍然活跃。每次按下清除按钮时,其他表单元素会不断重置,我只是无法使单选按钮工作。 (如果重要,请使用Chrome。)

2 个答案:

答案 0 :(得分:0)

您应ng-modelselectedStatus一起使用ng-checked,因为单选按钮上的{{1}}仅作为默认值首次使用,

答案 1 :(得分:0)

好的,我认为使用AngularJS示例:https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

首先,我不应该使用ng-checked来选择其中一个单选按钮,而是在控制器中我应该将ng-model值设置为我想要选择的按钮的“value”属性。其次,对于模型,我需要将“selectedStatus”值保存在JavaScript对象中,因为某些原因我不能使用标量:

$scope.radio = {
    selectedStatus : "either"
};

而不是

$scope.selectedStatus : "either"

最后,我不需要使用ng-value属性,因为我使用ng-repeat中的静态值来设置每个按钮的值。但是,其他用户的情况可能会有所不同,使用Plunker上的AngularJS样本可以让人更好地了解值或ng值是否更合适。无论如何,我更新了单选按钮脚本:

      Status: <span class="radio" ng-repeat="button in statusList">
            <input type="radio" name="status" ng-model="radio.selectedStatus" value="{{button.value}}"/>{{button.name}}
        </span>