如何在AngularJS中获取多个复选框的值?

时间:2016-12-08 11:44:14

标签: javascript angularjs

在我的应用中,我有7个复选框。我想获取所选复选框的值并存储到对象中。如果取消选择,我想在对象中删除它。

HTML

<span ng-repeat="days in selectDays">
    <input type="checkbox" id="{{days}}" ng-model="daysSelected"/>
    <label for="{{days}}">{{days}}</label>
</span>

控制器

$scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$scope.selectedList = {}; //this is the object to store the selected checkbox values

3 个答案:

答案 0 :(得分:7)

以下代码是一种简单的方法 - &gt;检查这个plunker。此示例为您提供了一个非常简单的KISS principle处理AngularJS中多个自动生成的复选框。

模板

message: "&6%player% just launched the cow party!"

作用域

<span ng-repeat="day in selectDays">
    <input type="checkbox" id="{{day}}" ng-model="selectedList[day]"/>
    <label for="{{day}}">{{day}}</label>
</span>
<button ng-click="submit()">Submit</button>

答案 1 :(得分:0)

    $scope.checkFun= function(data) {


                    for(var i in data){                                                                              
                       if(data[i].SELECTED=='Y'){ 
                          $scope.selectedList.push(data[i]);  
                         }
                        if(data[i].SELECTED=='N'){  
                          $scope.selectedList.splice(data[i]);
                         }
    }

<input type="checkbox" id="{{days}}" ng-model="selectDays.SELECTED" ng-true-value="'Y'" ng-false-value="'N'" ng-click="checkFun(selectDays)">

答案 2 :(得分:0)

我创建了一个jsfiddle,只要单击一个复选框调用一个函数,它就会使用角度的ngChange指令。代码看起来像这样

<div ng-controller="MyCtrl">
<span ng-repeat="day in selectDays">
    <input type="checkbox" id="{{day}}" ng-model="daysSelected" ng-change= "change(day)"/>
    <label for="{{day}}">{{day}}</label>
</span>
<span ng-repeat="day in selectedList">
<div>
{{day}}
</div>

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$scope.selectedList = []; 
$scope.change = function(day) {
var indexOfDay = $scope.selectedList.indexOf(day); 
    if(indexOfDay === -1) {
        $scope.selectedList.push(day)
    } else {
        $scope.selectedList.splice(indexOfDay, 1)
    }
 }
}