在 HTML 表单中,我需要跟踪哪些复选框被选中,以便我可以将其插入要发布到后端的查询对象中。
我在 $scope 的数组中有以下三个复选框:
$scope.typeCheckBoxes = [
{label: "A", val: true},
{label: "B", val: false},
{label: "C", val: false}
];
下面是我用于呈现表单中的复选框的模板:
<span ng-repeat="chk in typeCheckBoxes">
<input type="checkbox" ng-model="chk.val" id="chk.label" ng-change="addType(this)" />
<label>{{chk.label}}</label>
</span>
在我的 Controller 中,我尝试创建函数 addType() 以将选中的复选框添加到我的查询对象:
$scope.queryObj = {
types: []
};
$scope.addType = function(e) {
var selectedBox = angular.element(e.id); // not working
if (selectedBox) {
$scope.queryObj.types.push(selectedBox);
}
};
但是,我不确定如何获取选中复选框的 id
。非常感谢您的帮助。
最佳答案
首先你缺少的是,你应该在范围内编写 addType
函数,以便在复选框更改时触发它(因为你使用 ng-change
指令将在当前范围内查找函数)
您可以在 Controller 中获取 ng-change 事件,并对对象执行简单的 forEach 操作。
代码
$scope.addType = function(){
angular.forEach($scope.typeCheckBoxes, function(value, index) {
if(value.val)
console.log('value.id');//here you can get selected value
});
}
更新:
实际上,您可以通过使用 Angular $filter
服务来过滤数组并通过它获取已检查和未检查列表,从而获得所需的已检查/未检查标签列表。然后为了获得标签,您需要执行一个 for 循环。
代码
$scope.$watch('typeCheckBoxes', function (newObj, oldObj) {
var types,
checked = $filter('filter')(newObj, {'val': true}), //checked list
unchecked = $filter('filter')(newObj, {'val': false}); //unchecked list
console.log(checked);
console.log(unchecked);
for (var i=0; i< checked.length; i++) {
types.push(checked[i].label); //adding checked labels to type array
}
}, true);
这对你有帮助,谢谢。
关于javascript - AngularJS:跟踪选中了哪个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28097770/