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



我有两个标准: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);
});

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

为了满足您的需求,您只需要使用一个带有ng模型的无线电盒子,它将开箱即用。

使用单选按钮:

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输入类型=无线电指令API参考

最新更新