Skip to content Skip to sidebar Skip to footer

Auto Select And Collect Checkbox Values In Array

I'm having a problem with setting (checking) and fetching array of data from view to my model. Let me explain my problem further with code. This is my controller where i provide wo

Solution 1:

Add a function to your controller and call it to initialize your model ($scope.myData), like this:

Controller

$scope.myData = [];
function getMyData() {
   angular.forEach($scope.workDays, function(day) {
     var newDay = {
       name: day.name,
       selected: $scope.selectedDays.indexOf(day.value) >= 0
     };
     $scope.myData.push(newDay);
   });
}

getMyData();

Then you can simplify your markup like this:

Markup

<div class="checkbox">
  <label ng-repeat="w in myData">
    <input type="checkbox" ng-model="w.selected"> {{w.name}}&nbsp;&nbsp;
  </label>
</div>

You can see this working here.


Solution 2:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.workDays = [{
    name: 'Monday',
    value: 1
  }, {
    name: 'Tuesday',
    value: 2
  }, {
    name: 'Wednesday',
    value: 3
  }, {
    name: 'Thursday',
    value: 4
  }, {
    name: 'Friday',
    value: 5
  }, {
    name: 'Saturday',
    value: 6
  }, {
    name: 'Sunday',
    value: 7
  }, ]
  $scope.selectedDays = [1, 3, 4, 6];
  $scope.myData = $scope.selectedDays;

  $scope.getData = function(Day) {
    var index = $scope.myData.indexOf(Day);

    if (index < 0) {
      $scope.myData.push(Day)
      console.log('myData', $scope.myData);
    } else {
      $scope.myData.splice(index, 1)
      console.log('myData', $scope.myData);
    }
  }
  $scope.IsChecked = function(Day) {


    var index = $scope.selectedDays.indexOf(Day);

    if (index > -1) {

      return true
    } else {
      return false
    }
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <link data-require="bootstrap-css@3.3.6" data-semver="4.0.0-alpha.2" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" />
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>
  <label>Working days</label>
  <div class="checkbox">
    <label ng-repeat="w in workDays" ng-model="myData">
      <input type="checkbox" ng-value="w.value" ng-click="getData(w.value)" ng-checked="IsChecked(w.value)" />{{w.name}}
    </label>
  </div>

</body>

</html>

Fixed.


Post a Comment for "Auto Select And Collect Checkbox Values In Array"