http://plnkr.co/edit/b1v87pUEykOJN4mKLFHa?p=preview
My goal is to manage two arrays: one coming from an API called apiArray
, and the other, toggleArray
, will hold selected items from apiArray
.
The function selectBtn
is meant to toggle items in and out of the array. Currently, I am able to add items to toggleArray
, but not remove them when clicking on the same button.
I'm looking for a more efficient way to check if an item is not in the array, then add it, and if it is in the array, then remove it.
var vs = $scope;
vs.message = "Add and remove objects from array:";
vs.toggleArray = [];
var btnInArray = false;
vs.apiArray = [
{ name: 'AAA' },
{ name: 'BBB' },
{ name: 'CCC' }
];
vs.selectBtn = function(btnObj) {
console.log(btnObj.name);
function checkUpdateToggleTags(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
btnInArray = checkUpdateToggleTags(btnObj, vs.toggleArray);
if (btnInArray) {
// check the toggleArray and if obj from listToDelete is there
// remove that obj from toggleArray
for(var i = 0; i < vs.toggleArray.length; i++) {
var obj = vs.toggleArray[i];
if (vs.toggleArray.indexOf(obj.term) !== -1) {
vs.toggleArray.splice(i, 1);
i--;
}
}
} else {
vs.toggleArray.push(btnObj);
}
console.log(btnInArray);
console.log(vs.toggleArray);
};