angularjs复选框控制台中的错误响应

时间:2018-08-04 17:23:12

标签: angularjs checkbox

我有两个条件: 1)一次只能选择两个框之一。 2)捕获所选框的名称。

但是,当我打印出复选框对象列表时,它们是正确的,但是当我在控制台中签入时,它们是不正确的。例如,

HTML:

<div ng-repeat="treatment in treatment_list">
 <input type="checkbox" value="{{treatment.name}}"
        ng-model="treatment.checked"
        ng-click="updateTreatment($index, treatment_list);
                  checkedTreatment(treatment_list)">
 <label>Treatment {{treatment.name.toUpperCase()}}</label></input><br>
</div>
{{treatment_list}}

控制器:

$scope.treatment_list = [
    {
      name: 'a',
      checked: false
    }, {
      name: 'b',
      checked: false
    }
  ];

$scope.updateTreatment = function(position, treatment_list) {
    console.log(treatment_list);
    angular.forEach(treatment_list, function(treatment, index) {
      console.log(treatment.name, treatment.checked);
      if (position != index) {
        treatment.checked = false;
      }
    });
  };

$scope.$watch('treatment.checked', function (treatment) {
    console.log(treatment);
  });

柱塞: https://plnkr.co/edit/Hkb4IeKxi0TRqHRJA4JN?p=preview

2 个答案:

答案 0 :(得分:1)

为了满足您的要求,您应该只使用带有ng-model的单选框,它将为您方便地使用。

答案 1 :(得分:1)

改为使用单选按钮:

angular.module("app",[])
.controller('ExampleController', function($scope) {
      $scope.color = {
        name: 'blue'
      };
      $scope.specialValue = {
        "id": "12345",
        "value": "green"
      };
      $scope.colorChange = function(color) {
          console.log(color);
      };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<form name="myForm" ng-controller="ExampleController">
  <label>
    <input type="radio" ng-model="color.name" value="red"
           ng-change="colorChange(color.name)" />
    Red
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" ng-value="specialValue"
           ng-change="colorChange(color.name)" />
    Green
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" value="blue"
           ng-change="colorChange(color.name)" />
    Blue
  </label><br/>
  <tt>color = {{color.name | json}}</tt><br/>
 </form>
 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</body>

有关更多信息,请参见AngularJS input type=radio Directive API Reference