Link several checkboxes with ng-model

1

I request your help because I have not managed to bind between several checkboxes and the data. I have tried it in several ways and this has been my result:

HTML

<label ng-repeat="teams in teams" class="checkbox-inline">
  <input type="checkbox"  
    value="{{teams.name}}" ng-model="data.id"> {{fruit.id}}
</label>

Controller

$scope.teams = [
    { name: "Red", id: 0, }, 
    { name: "Blue", id: 1,}, 
    { name: "Green", id: 2,},
    { name: "Yellow", id: 3, }, 
    { name: "Orange", id: 4,}, 
    { name: "Purple", id: 5}
];                    
$scope.data = [0,1];   

//Posible solucion:
$scope.selectF = function selectF(){
  for (var i=0;i<data.length;i++){
   for (var j=0;j<teams.length;j++) {
      if(data[i].id === teams[i].id ){
        return true;
      }
     return false;
    }
  } 
}
    
asked by Gdaimon 29.09.2016 в 19:59
source

1 answer

1

I think it's a very sophisticated solution. To make bindings with checkbox and ng-model use values true or false . If you must convert these values use a $watch like the one below. Notice that I have not written a single line of code, only the one necessary to initialize the collections.

angular.module('app', [])
  .controller('CheckBoxCtrl', function($scope) {
    $scope.teams = [{
      name: "Red",
      id: 0,
    }, {
      name: "Blue",
      id: 1,
    }, {
      name: "Green",
      id: 2,
    }, {
      name: "Yellow",
      id: 3,
    }, {
      name: "Orange",
      id: 4,
    }, {
      name: "Purple",
      id: 5
    }];
    $scope.data = [true, false, true, false, true, false];

    $scope.$watch('data', function(val) {
      console.log(val);
    }, true);
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="CheckBoxCtrl">
  <label ng-repeat="team in teams" class="checkbox-inline">
    <input type="checkbox" value="{{team.name}}" ng-model="data[team.id]">{{team.name}}
  </label>
</div>

If you want something more complex than that, use checklist-model

    
answered by 29.09.2016 / 20:37
source