How to use an input checkbox in the angular using Array?

4

I'm trying to use a Array in a input[type=checkbox] with Angle 1, but I was not successful.

angular.module('app', [])


.controller("Ctrl", function ($scope){

  $scope.campos = [{nome: "Brasil"}, {nome: "Argentina"}, {nome: "Paraguai"}];
  
  $scope.campos_selecionados = [];

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script><divng-app="app" ng-controller="Ctrl">
  <label ng-repeat="campo in campos">
    <input type="checkbox" 
          ng-true-value="{{ campo }}"
          ng-false-value="undefined"
          ng-model="campos_selecionados[$index]">
    {{ campo.nome }}
  </label>
  
  
  <pre>{{ campos_selecionados | json }}</pre>
</div>

In the example above,% w_of%, even when the checkbox is not selected, is marked as Array .

How can I make my checkbox generate a null with the items that were selected?

    
asked by anonymous 31.07.2017 / 18:28

2 answers

4

My solution to this was not to use ng-model . Instead, I defined a function executed when there is a click on checkbox and check if the item is selected through indexOf in the ng-checked directive.

See:

angular.module('app', [])


.controller("Ctrl", function ($scope){

  $scope.campos = [{nome: "Brasil"}, {nome: "Argentina"}, {nome: "Paraguai"}];
  
  $scope.campos_selecionados = [];
  
  $scope.selecionar = function (campo)
  {
    var idx = $scope.campos_selecionados.indexOf(campo);
    
    idx >= 0 ? $scope.campos_selecionados.splice(idx, 1) : $scope.campos_selecionados.push(campo);
  };

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script><divng-app="app" ng-controller="Ctrl">
  <label ng-repeat="campo in campos">
    <input type="checkbox" ng-checked="campos_selecionados.indexOf(campo) >= 0" ng-click="selecionar(campo)">
    {{ campo.nome }}
  </label>
  
  
  <pre>{{ campos_selecionados | json }}</pre>
</div>
    
31.07.2017 / 18:28
4

It is possible to keep a property on the objects it controls whether it has been selected or not and treat when it is sent to the server.

angular.module('app', []).controller("Ctrl", function ($scope){

  $scope.campos = [{nome: "Brasil"}, {nome: "Argentina"}, {nome: "Paraguai"}];
    
  $scope.enviar = function() {
    const camposSelecionados = $scope.campos
                                .filter(e => e.selecionado)
                                .map(e => ({ nome: e.nome }));
                                
    console.log(camposSelecionados);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app" ng-controller="Ctrl">
  <label ng-repeat="campo in campos">
    <input type="checkbox" ng-model="campo.selecionado">
    {{ campo.nome }}
  </label>  
  
  <pre>{{ campos | json }}</pre>  
  
  <button ng-click="enviar()">Enviar</button>
</div>
    
31.07.2017 / 19:07