How to get multiple checkbox values โ€‹โ€‹in AngularJS?

In my application, I got 7 flags. I want to get the value of the selected checkbox and save it in the object. Ff he is not selected. I want to delete it in an object.

HTML

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

controller

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

The following code is a simple approach -> check this plunker . In this example, you will get a very simple KISS principle for handling check boxes with auto-generated in AngularJS.

Template

<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>

Sights

//default states
$scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$scope.selectedList = {};

/**
 * Action
 */
$scope.submit = function () {
    angular.forEach($scope.selectedList, function (selected, day) {
        if (selected) {
           console.log(day);
        }
    });
};
+6
source
    $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)">
0
source

jsfiddle, ngChange angular , , . :

<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)
    }
 }
}
0

Source: https://habr.com/ru/post/1663224/


All Articles