JSON array with Angularjs checkbox

Asked

Viewed 475 times

3

I am trying to form a JSON with what is selected by checkbox, but when I select it inserts, but when I try to remove the check in, it inserts again. The correct would be to work in that way, but forming a JSON array and not just words or numbers.

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


crud.controller('CadUserController',['$scope', function ($scope) {
	
$scope.dbProfiles = [{"id":1,"nome":"Adminstrador"},{"id":2,"nome":"Tabeliao"},{"id":3,"nome":"Substituto"},{"id":4,"nome":"Escrevente"},{"id":5,"nome":"Caixa"},{"id":6,"nome":"Auxiliar"}];

	  // selected fruits
	  $scope.selection = [];
	  var profiles= [];

	  // toggle selection for a given fruit by name
	  $scope.toggleSelection = function toggleSelection(profileId) {
	    var idx = $scope.selection.indexOf({"idProfile":profileId});
	    // is currently selected
	    if (idx > -1) {
	      $scope.selection.splice(idx, 1);
	    }
	    // is newly selected
	    else {
	      $scope.selection.push({"idProfile":profileId});
	    }
	  };
 }]);
<div ng-app="crud"> 
<div ng-controller="CadUserController" class="col-md-9 form-group">
   <label for="perfil">Perfil</label><br>            

   <span ng-repeat="profile in dbProfiles">
     <input type="checkbox" value="{{profile.id}}" 
            ng-checked="selection.indexOf(profile.id) > -1" 
            ng-click="toggleSelection(profile.id)"> {{profile.nome}}

   </span>
   {{selection|json}}
</div>
  </div>
<script src="resources/js/angular/angular.min.js"></script>

  • You couldn’t implement the example you posted yourself?

  • You need a json or you just need to know what has been checked?

  • i managed to implement, but I need something more complete, instead of [1,2,4] I need [{"profile":1},{"profile":2},{"profile":3}]

1 answer

2


I didn’t understand it very well, but from what I saw in a comment you wanted something more "complete" and not just take the [1,2,3].

See if this example I put together can help you: http://jsfiddle.net/sinkz/HB7LU/21023/


Updated

I think I could understand the problem a little better, in case the example above does not solve, try this: http://jsfiddle.net/sinkz/HB7LU/21024/

In the function that is called in the ng-click passes a String along with the profile code: ng-click="toggleSelection('profile: '+profile.id)"

That way the result will be like this:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.