Steve Steve - 2 months ago 12
AngularJS Question

Angular JS: Add and remove terms from checkboxes in ng-repeat?

I have a miller column constructed in Angular and Bootstrap.

http://codepen.io/smlombardi/pen/WGwGbY

In the second column, clicking the word (link) opens the third column, but I need to have the checkbox add that word to an array of search terms.

If the checkbox is UN-checked, I need to remove that word from the array of search terms. As you can see in the pen, I have the adding part working, but un-checking the box adds the word again.

I realize what I need to do is somehow check the state of the checkbox and if it's true add the word and if it's false check the array for the word (string) and pop it out of the array.

I can't figure out how to check only the checkbox that was clicked.

<div class="col-xs-3 inner-column">
<div class="panel panel-default">

<div class="list-group">
<div class="list-group-item" ng-class="{active: $index === pmt.millercolumn.level1Selected }" ng-repeat="level1 in pmt.millercolumn.level1 track by $index">
<input type="checkbox" ng-model="activeSearchTerm" ng-change="pmt.change($index)" id="ng-change-example1" />
<a href="" ng-click="pmt.getSublevel2($index)" >
{{level1.name}}
<i class="pull-right fa fa-angle-right fa-lg"></i>
</a>
</div>
</div>
</div>




the
ng-change
on the checkbox calls:

_this.change = function (index) {
var searchTerm = _this.millercolumn.level1[index].name;
_this.searchTerms.push(searchTerm);
};

Answer

Add this code in place of your _change function it works for sure

 _this.change = function (index) {
    console.log('Clicked on', _this.millercolumn.level1[index].name);
    var searchTerm = _this.millercolumn.level1[index].name;
    var searchIndex = _this.searchTerms.indexOf(searchTerm);
    if (searchIndex == -1) {   // If new push
       _this.searchTerms.push(searchTerm);
    }
    else {                    // Else remove item
      _this.searchTerms.splice(searchIndex, 1);
    }
    console.log(_this.searchTerms);
  };

Working codepen demo : http://codepen.io/krishcdbry/pen/EgKgBv