在AngularJS中,如何取消选中单选按钮以使所有对象变为false

时间:2015-11-13 19:30:12

标签: javascript angularjs radio-button

我有一个包含很多"联系人"里面的物体。只有一个联系人可以是主要联系人(主要:真实)。

我还有一个单选按钮,用于选择哪个联系人是主要联系人。

问:如何将一个联系人设为主要联系人并停用所有其他联系人(主要:假)?所以只有一个对象具有属性(primary:true),其余为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>

2 个答案:

答案 0 :(得分:4)

您可能希望在输入中添加ngChange事件,并在将其设置为true时将所有其他输入更改为false。我在这里更新了你的Plnkr: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而不是名称字段进行比较。

答案 1 :(得分:2)

您可以定义新的范围属性

$scope.primary = null

然后你可以定义一个监听器

$scope.$watch("primary", function(value) {
  $scope.addContList.forEach(function(contact) {
    contact.primary = angular.equals(value, contact);
  })
})

您可以在定义列表

后定义默认值
$scope.primary = $scope.addContList[0];

并在html中更改

中的输入行
<input type="radio" value="" name="ui_cont" ng-model="$parent.primary" ng-value="contact">

您需要使用$parent.primary代替primary,因为ng-repeat定义了新的子范围。

请参阅http://plnkr.co/edit/5pvatBNwnrJhGzKhOIys?p=preview