在AngularJS中如何取消选中单选按钮以使所有对象变为假 [英] In AngularJS how to uncheck a radio button to make all objects become false

查看:39
本文介绍了在AngularJS中如何取消选中单选按钮以使所有对象变为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中包含许多接触"对象.主要联系人只能是一个联系人(primary:true).

I have an array with many "contact" objects inside. Only one contact can be the primary contact (primary: true).

我还有一个单选按钮,可以选择哪个联系人为主要联系人.

I also have a radio button to select which contact is the primary.

问:如何使一个联系人成为主要联系人,并停用所有其他联系人(主要联系人:否)?所以只有一个对象具有属性(primary:true),其余的则为false?

Q: How can I make one contact primary and deactivate all of the others (primary: false)? so only one object have the property (primary: true) and the rest false?

我的示例: http://plnkr.co/edit/Y3as4SXv2ZGQSF39W8O6?p=preview

.controller('ExampleController', ['$scope',
        function($scope) {
        $scope.addContList = [
            {
                email: "q@q.com",
                jobTitle: "clerk",
                name: "nico2",
                phone: "1",
                primary: true
            },
            {
                email: "a@a.com",
                jobTitle: "director",
                name: "david",
                phone: "1",
                primary: false
            }
        ];
          $scope.$watch('addContList', function() {
            console.log('changed', JSON.stringify($scope.addContList, null, 2))
          }, true)

        }
      ]);

这是视图

<tr ng-repeat="contact in addContList">
          <td>
            <label class="radio-inline">
              <input type="radio" value="" name="ui_cont" ng-model="contact.primary" ng-value="true">
            </label>
          </td>
          <td>{{ contact.name }} value = {{contact.primary}} </td>
          <td>Edit</td>
          <td>Delete</td>
        </tr>

推荐答案

您可能想在输入中添加一个 ngChange 事件,并将其他所有输入设置为true时将其更改为false.我在这里更新了您的Plnkr: http://plnkr.co/edit/7gxI7if9nC7hAMQES1eu?p=preview

You would want to add an ngChange event to your input and change all other inputs to false when one gets set to true. I have updated your Plnkr here: http://plnkr.co/edit/7gxI7if9nC7hAMQES1eu?p=preview

<input type="radio" value="" name="ui_cont" ng-change='changeOnPrimary(contact)' ng-model="contact.primary" ng-value="true">

然后在您的控制器中:

$scope.changeOnPrimary = function(selectedContact) {
  // iterate over your whole list
  angular.forEach($scope.addContList, function(contact) {
    // set primary to false for all contacts excepts selected
    if (selectedContact.name !== contact.name) {
      contact.primary = false;
    }
  });
}

请注意:我比较对象名称字段的唯一原因是因为没有唯一的标识符可用于比较.在真实代码中,您希望与ID而不是名称字段进行比较.

Please note: the only reason I'm comparing the name field of the object is because there is no unique identifier to compare with. In real code, you would want to compare against an ID rather than a name field.

这篇关于在AngularJS中如何取消选中单选按钮以使所有对象变为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆