I have an array of strings, lets call them barcodes. I'm using to Angular.js to loop through this array and display the strings and a input field. I need to use angular to validate that when a user enters a new barcode into this input field that it's identical to the string that's displayed right next to it, see example below. I attempting a ng-change event right now which would work if it was just one input field, but because I'm using ng-repeat I cannot make that work. I'm guessing I need to build a directive? I'm new with angular so any help or suggestions would be great. Thanks!
EDIT:
For my purpose I need to alert the user if they enter an incorrect input. My case is unique as the user will not be typing in the input field.. they will be using a barcode scanner, so essentially it is the same as a copy/paste. @KKKKKKKK answer below gets me very close. I made some subtile changes (below) but now this introduces other bugs. with this code below I get the proper alert message but it fires three times? I cannot figure out why..
HTML:
<input type="text" class="form-control matching" ng-model-options="{ updateOn: 'blur' }" ng-model="item.barcodeInput" placeholder="Barcode">
<div ng-show="!isEqualToBarCode($index, item.barcodeInput)"> Error: Value not the same! </div>
In Angular Controller:
$scope.isEqualToBarCode = function(index, val) {
if(val === null || val === undefined) return true;
if($scope.barcodes.A_adaptors[index] !== val.trim()) {
console.log("wrong");
alert("Incorrect Barcode, Try Again.");
val = "";
}
return $scope.barcodes.A_adaptors[index] === val.trim();
}
Just pass in the $index
to your command and then compare it to your array. (Sorry for blind coding errors)
Controller:
$scope.isEqualToBarCode = function(index, val) {
//if val is empty, don't display error
if(val === null || val === undefined) return true;
return $scope.barcodeArray[index].barcodeVal === val.trim();
}
HTML:
<div ng-repeat="item in barcodeArray">
{{item.barcodeVal}}
<input ng-model="item.barcodeInput" ng-model-options="{ updateOn: 'blur' }" />
<div ng-show="!isEqualToBarCode($index, item.barcodeInput)">
Oh no! Value not the same!
</div>
</div>
If you want to set the form validity based on inputted values, then, yes, you would need to write a custom directive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.