【问题标题】:AngularJS uncheck radio buttonAngularJS取消选中单选按钮
【发布时间】:2017-05-05 10:44:39
【问题描述】:

我曾尝试使用 ng-dblclick、$event 等查看其他解决方案,但它们似乎都不适合我。

我在表格的 ng-repeat 中有两个单选按钮。我有一个字段用于设置哪个单选按钮应该处于活动状态。仅使用 ng-change 即可正常工作,但我也希望能够取消选择任何单选按钮。

Ng-change 不会触发此操作,因此我也添加了一个用于 ng-click 的代码,并且乱七八糟的代码可以正常工作,但这样做有没有更简洁的方法?

<td>
    <div class="inline-group">
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-change="save(item, false)" ng-click="save(item, true)" ng-model="item.Stage" value="Started">
            <i></i> Started
        </label>
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-change="save(item, false)" ng-click="save(item, true)" ng-model="item.Stage" value="Completed">
            <i></i> Completed
        </label>
    </div>
</td>

控制器

var runOnce = false;

$scope.save = function (item, uncheck) {
    if (runOnce) {
        return;
    }

    if (uncheck) {
        item.stage = null;
    }
    else {
        runOnce = true;
    }

    ...
    .$promise.then(function (result) {
        ...
        runOnce = false;
        ...
     });
    ...

【问题讨论】:

标签: javascript angularjs radio-button


【解决方案1】:

documentation

<div class="inline-group">
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="true">
            <i></i> Started
        </label>
        <label class="radio">
            <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="false">
            <i></i> Completed
        </label>
    </div>

对于真/假选择,请使用复选框而不是单选按钮

更新

使用枚举,在您的范围内:

$scope.stageEnum = { Started: 0, Completed: 1 };

你的看法:

<div class="inline-group">
            <label class="radio">
                <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="stageEnum.Started">
                <i></i> Started
            </label>
            <label class="radio">
                <input type="radio" name="stage{{$index}}" ng-model="item.Stage" value="stageEnum.Completed">
                <i></i> Completed
            </label>
        </div>

【讨论】:

  • 是的,我使用复选框来选择真/假,但我想要一个解决方案,我可以轻松添加或删除更多阶段,而无需更新数据库。
  • 好的,你可以使用枚举
【解决方案2】:

单选按钮一次只能选择一个,并且一旦选中,用户就不能取消选中(除非您以编程方式进行,如您所尝试的那样)。也许,更清洁方法的一个例子是:

<input type="radio" ng-model="checked" value="500" ng-click="uncheck($event)" />
<input type="radio" ng-model="checked" value="1000" ng-click="uncheck($event)" />
<input type="radio" ng-model="checked" value="1500" ng-click="uncheck($event)" />

在您的控制器中:

$scope.uncheck = function (event) {
    if ($scope.checked == event.target.value)
        $scope.checked = false
}

演示:http://jsfiddle.net/8s4m2e5e/3/

【讨论】:

  • 嗯,是的,我看到了这个解决方案,但不知道如何修改它以便它适用于我的情况
猜你喜欢
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 2012-01-23
  • 2012-03-17
  • 2016-05-24
相关资源
最近更新 更多