When comparing a variable with an array, specifically $scope.object.id
and $scope.groepen.id
, I am using an if statement following a for loop. If $scope.object.id
matches any of the IDs in $scope.groepen.id
, then the corresponding index of $scope.overlap
should be set to true.
I also have another if statement to check if any elements in $scope.overlap
are true. If at least one element is true, then $scope.bestaand
is set to true; otherwise, it is set to false.
for (var i = 0; i < $scope.groepen.length; i++) {
if ($scope.object.id === $scope.groepen[i].id) {
$scope.overlap[i] = true;
if ($scope.overlap[i]) {
$scope.bestaand = true;
}
else {
$scope.bestaand = false;
}
}
else {
$scope.overlap[i] = false;
}
}
The console log confirms that $scope.overlap
displays the correct values (all indexes are false when no match is found). However, the issue arises when $scope.bestaand
remains true even when no match is found.
To validate this behavior, Angular form validation is applied as shown below:
<div class="col-md-3" ng-class="{ 'has-error' : bestaand }">
<label class="control-label" for="textinput">Groepsnaam</label>
<input id="groepen" name="groepen" type="text" class="form-control input-md" ng-model="object.id" ng-minlength="4" ng-maxlength="16" ng-change="checkOverlap()" required>
<p ng-show="bestaand" class="help-block">Deze groepsnaam bestaat al!</p>
</div>
What mistake could be leading to this behavior?
Edit:
I reorganized the placement of my if statements. Updated code is shown below:
for (var i = 0; i < $scope.groepen.length; i++) {
if ($scope.object.id === $scope.groepen[i].id) {
$scope.overlap[i] = true;
}
else {
$scope.overlap[i] = false;
}
if ($scope.overlap[i]) {
$scope.bestaand = true;
console.log("works")
}
else {
$scope.bestaand = false;
console.log("doesnt work")
}
}
The console log reveals the following results:
https://i.sstatic.net/0GOkY.png
It appears that the value does become true, but it gets overwritten (when using a value matching the second item in the array). However, if a value matching the last item in the array is used, it works correctly.