Why splicing doesn't work properly in angular js

I am trying to make one demo in which I have one checkbox . I can display a list using ng-repeat.

What do I need if the user clicks on one checkbox (only one checkbox is selected) .it displays only one column width (100%). Which user checked the two columns, it displays two columns of equal width (50%). if the user checks three columns, he displays three columns of the same width. As if the user had set four checkboxes, it shows four columns with the same width. Normally checked ( checked: true ) ..

  • My first step is to uncheck the box with a check of "3" ... but after unchecking it still shows why? I already use splicing. method?

here is my code http://codepen.io/anon/pen/adBroe?editors=101

init(); function init(){ for(var i =0;i<self.data.length;i++){ var obj=self.data[i]; if(obj.checked) { self.selectedList.push(obj); } } alert('starting '+self.selectedList.length) } self.checkBoxClick=function(obj,i){ if(obj.checked) { alert('if') self.selectedList.push(obj); }else { alert('else'+i); self.selectedList.splice(i,1); } alert(self.selectedList.length); } }) 

here I am trying to display

  <div class='container-fluid'> <div class='row'> <div ng-repeat="i in vm.selectedList" class='col-xs-{{12/vm.selectedList.length}}'> {{i.name}} </div> </div> </div> 
+6
source share
2 answers

It could be a lot easier. In HTML, you don’t even need an ngChange handler, just bind to a checked property:

  <div class="checkbox" ng-repeat='v in vm.data'> <label> <input type="checkbox" ng-model='v.checked'> {{v.name}} </label> </div> 

and then display the columns using ngRepeat :

  <div ng-repeat="i in filteredList = (vm.data | filter:{checked:true})" class='col-xs-{{12/filteredList.length}}'> {{i.name}} </div> 

Thus, clear the controller without any logic, Angular having done all the necessary column filtering using the vm.data | filter:{checked:true} vm.data | filter:{checked:true} .

Demo: http://codepen.io/anon/pen/bEBydL?editors=101

+4
source

This is because you are trying to remove it from the second index, while learning 3 is present in the 0th index.

 else { alert('unchecked '+i); var index = self.selectedList.indexOf(obj); self.selectedList.splice(index,1); } 

change your part. and it will work fine.

http://codepen.io/anon/pen/yeVWeQ?editors=101

+2
source

All Articles