I’m using angular.js and jQuery to validate user inputs in a form that is created using an ng-repeat. So essentially I have an array of strings(barcodes) I loop through and display, I also display an input field. The user is going to use a barcode scanner, think of it like a copy/paste effect, to enter strings into the input fields. If the barcode doesn’t match the string thats next to it than it should alert the user and clear the input field. I have the code below that uses ng-model-options ‘Blur’ to perform this and it almost works. Right now it alerts the user three times every time an inputs is incorrect. I cannot figure out why it fires three times? there must be a more elegant way of achieving this validation with angular/jQuery? maybe a directive? I’m new with angular so any help is greatly appreciated, Thanks!
HTML:
<div ng-repeat="(index, val) in barcodes.barcodes track by $index">
<div class="form-group row" ng-show="barcodes.barcodes[index]">
<div ng-if="barcodes.barcodes[index] != 'X'">
<label class="col-sm-3 form-control-label" style="margin-top:5px"> {{ barcodes.barcodes[index] }} </label>
<label class="col-sm-2 form-control-label" style="margin-top:5px"> {{ barcodes.A_adaptors[$index+8] }} </label>
<div class="col-sm-1" style="margin-top:5px">
<button class="btn btn-xs btn-default hvr-pop" data-toggle="dropdown" ng-click="getIndex($index+8)"><i class="fa fa-cogs" aria-hidden="true" style="color:#DF3D42"></i></button>
<ul class="dropdown-menu" role="menu">
<div ng-repeat="x in barcodes.B_adaptors">
<li class="text-center" ng-click="replace(x)" id="B_adaptors">{{ x }}</li>
</div>
</ul>
</div>
<div class="col-sm-6">
<input type="text" class="form-control matching" ng-model-options="{ updateOn: 'blur' }" ng-model="item.barcodeInput" placeholder="Barcode" required>
<div ng-show="!isEqualToBarcode($index+8, item.barcodeInput)"> Error: Barcode not the same! </div>
</div>
</div>
</div>
</div>
JAVASCRIPT: (in controller)
$scope.isEqualToBarcode = function(index, val) {
if(val === null || val === undefined) return true;
if($scope.barcodes.A_adaptors[index] !== val.trim()) {
console.log("wrong", val);
alert("Incorrect Barcode, Try Again.");
val = "";
}
return $scope.barcodes.A_adaptors[index] === val.trim();
}