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 = [];
functiongetMyData() {
   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">
  <labelng-repeat="w in myData"><inputtype="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) {

      returntrue
    } else {
      returnfalse
    }
  }
});
<!DOCTYPE html><htmlng-app="plunker"><head><metacharset="utf-8" /><title>AngularJS Plunker</title><linkdata-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><linkrel="stylesheet"href="style.css" /><scriptdata-require="angular.js@1.4.x"src="https://code.angularjs.org/1.4.9/angular.js"data-semver="1.4.9"></script><scriptsrc="app.js"></script></head><bodyng-controller="MainCtrl"><p>Hello {{name}}!</p><label>Working days</label><divclass="checkbox"><labelng-repeat="w in workDays"ng-model="myData"><inputtype="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"