I'm just getting started with learning angularjs and I would appreciate some kindness as a beginner.
Currently, I am working on creating a poll app using angular.
In my project, I have an array scope named items
, which holds all the items to be added to the poll.
$scope.items = []
I am writing an error handling script to let the user know if a specific poll item already exists in the items
array. Due to the format of how my items are added (e.g., 1. item1
, 2. item2
), I cannot directly use the indexOf
method in the array to search for existing items. Instead, I need to loop through all indexes in the items[] array and perform the indexOf
method within each index to check for duplicates.
The code I have should return true
if an item is found in the array and false
if it isn't:
//number of items in the array
var itemNum = $scope.items.length + 1;
//the item entered by the user
var toBeAdded = $scope.pollItem;
//search for existing item in items[] array
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 to the poll if findItem() returns false
if (!findItem) {
$scope.items.push(itemNum.toString() + " " + toBeAdded);
$scope.pollItem = "";
focus('pollItem');
} else {
alert('item already exists');
}
However, this code always returns "true" even when my items array is empty. I can't figure out what I'm doing wrong. Any help would be greatly appreciated.
Thank you to anyone who can assist me.