I'm starting to learn angularjs (I'm a beginner so please be kind).
I'm making a poll app and I'm using angular to do this
I have a array scope called items which consists all the items that will be added to the poll.
$scope.items = []
I'm making an error handling script which would inform the user if a specific poll item is already at the items array and I cannot do the indexOf method in the array directly to search if an item already exists since my code would be adding numbers into the array directly like 1. item1 , 2. item2 , 3. item3 so I want to search through all indexes in the items[] and do the indexOf method inside the index to see if an item already exists.
I have this code which supposedly return true if an item already exists inside the array and would return false otherwise:
//number of items in the array
var itemNum = $scope.items.length + 1;
//the item which the user entered
var toBeAdded = $scope.pollItem;
//try to search the items[] array if an item already exists
var findItem = function (){
for (var i = 0; i < itemNum-1; i++) {
if ($scope.items[i].indexOf(toBeAdded) >= 0) {
return true
}else{
return false
}
}
}
//add the item into the poll if findItem() function returns false
if (!findItem) {
$scope.items.push(itemNum.toString() + " " + toBeAdded);
$scope.pollItem = "";
focus('pollItem');
}else{
alert('item already exists')
}
but instead it is always returning "true" (even if my items array is empty). I don't know what I'm doing wrong. Please help.
Thank you for anyone that can help me.