【问题标题】:ng-checked in a radio button in AngularJSng-checked 在 AngularJS 中的单选按钮中
【发布时间】:2018-08-21 20:57:53
【问题描述】:

在我的 Angular 应用程序中,我正在遍历一个集合并使用 input type="radio" 显示记录。

<tr ng-repeat="account in vm.pagedAccounts.items"
                ng-class="{ 'highlight': (account.rowIsSelected) }"
                <td>
                    <input
                        ng-model="account.rowIsSelected"
                        value="{{account}}"
                        name="selectedAccount"
                        ng-checked="account.rowIsSelected"
                        ng-change="vm.selectAccount(account)"
                        type="radio">
                </td>

在我的控制器中,我首先将所有帐户的 rowIsSelected 属性设置为 false。

response.data.results.forEach(function(account) {
   account.rowIsSelected = false;
});

所以,我只是确保无论何时 account.rowIsSelected 设置为某个值,都选中它。

这工作正常。

但是,在selectAccount函数中,如果点击不同的帐户,我想remove the previous all highlights and highlight the current one

    vm.selectAccount = function (account) {
        if (account.rowIsSelected) {

            //First set all false
            vm.pagedAccounts.items.forEach(function(account) {
                account.rowIsSelected = false;
            });

            var selectedAccount = vm.pagedAccounts.items
                .filter(function(x){
                    return x.id=== account.id;
                });

            //Then set only that accounts property to true
            selectedAccount[0].rowIsSelected = true;
        } 

但如果我点击同一行两次,it is no longer checked. I want to keep it checked and highlighted

怎么做? 我所做的一切看起来对吗? 请帮忙。

【问题讨论】:

  • 不要在同一个元素上使用 ng-checked 和 ng-model。我认为您应该始终使用 ng-model。
  • @PetrAveryanov 那我怎样才能让单选按钮选中它?
  • Angular 在单选按钮方面很时髦。您应该使用 ngModel 而不是 ngCheckeddocs.angularjs.org/api/ng/input/input%5Bradio%5D

标签: javascript angularjs radio-button


【解决方案1】:

试试这个。

vm.selectAccount = function (checkedItem) {
    var selectedAccount;
    vm.pagedAccounts.items.forEach(function(account) {
        if(checkedItem.id == account.id){
           selectedAccount = account;
           account.rowIsSelected = true;
        }else{
           account.rowIsSelected = false;
        }

    });
    //Then set only that accounts property to true
    selectedAccount[0].rowIsSelected = true;

}

【讨论】:

  • 如果我点击同一行两次,检查被删除。
【解决方案2】:

我认为你应该以不同的方式组织你的单选按钮,就像它推荐的 angularjs

类似:

<tr ng-repeat="account in vm.pagedAccounts.items"
    ng-class="{ 'highlight': vm.pagedAccounts.selected === account }">
    <td>
        <input
            ng-model="vm.pagedAccounts.selected"
            ng-value="account"
            type="radio">
     </td>
...

ng-model 的值等于ng-value 时,应该自动选择单选按钮,因此您不需要任何特定的逻辑或ng-checked 等。

【讨论】:

  • 不应该是`ng-value="{{account}}"吗?此外,该行正在突出显示,但单选按钮似乎没有被选中。
  • ng-value="{{account}} 你不需要括号,因为我们使用ng- 指令。您也可以避免ng-chage,例如。我更新了草稿,试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 2014-06-10
  • 1970-01-01
  • 2019-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多