I am using angular.js version 1.6.4. I created a directive to check on the server side, and I see that it fires when I load the form, which is incorrect. I only want to run my code when I change the value. My HTML code
<div class="col-xs-6"> <div class="controls"> <label class="control-label" ng-hide="editRetailTrackingForm.barcode.$dirty && editRetailTrackingForm.barcode.$error"> @Labels.barcode: </label> <input type="text" name="barcode" ng-model="currentItem.barcode" sm-code-unique-validator table-name="items" column-to-test="barcode" error-message="itemBarcodeErrorMessage" primary-key="currentItem.itemId" ng-model-options="{ updateOn: 'blur', debounce: { default : 500, blur: 0 }}" class="form-control" ng-maxlength="100" /> <div ng-class="{loading:editRetailTrackingForm.barcode.$pending}">@String.Format(Messages.validatingX, Labels.barcode)</div> <div ng-if="editRetailTrackingForm.barcode.$dirty"> <div ng-messages="editRetailTrackingForm.barcode.$error"> <div ng-message="maxlength"> <label class="field-validation-error control-label-error animate-show"> @String.Format(Messages.cannotExceed, Labels.barcode, "100") </label> </div> <div ng-message="smCodeUnique"> <div class="info-text-block-error"> {{itemBarcodeErrorMessage}} </div> </div> </div> </div> </div> </div>
and my directive code is very similar to http://www.codelord.net/2014/11/02/angularjs-1-dot-3-taste-async-validators/
return { require: "ngModel", scope: { primaryKey: "=?", tableName: "@", columnToTest: "@", errorMessage: "=?" }, link: function ($scope, element, attrs, ngModel) { ngModel.$asyncValidators.smCodeUnique = function (modelValue, viewValue) { if (!viewValue) { return true; } let codeObject = { id: $scope.primaryKey, tableName: $scope.tableName, columnToTest: $scope.columnToTest, code: viewValue }; return services.Http.put('api/items/checkCodeUniqueness', codeObject).then( function (response) { if (!response.data.isValid) { $scope.errorMessage = response.data.errorMessage; return services.Deferred.reject(response.data.errorMessage); } return true; } ); }; } };
When I debug my code, I see that the server-side code works several times when I just create an instance of the form (and donโt even open the correct tab where this field is).
So, how do I change my directive or ng-options to only activate checks when I change my value?
javascript html angularjs asynchronous
Naomi Sep 07 '17 at 17:08 on 2017-09-07 17:08
source share