In the current project I'm handling, there is a straightforward dialog for adding a custom employee to a business application. The modal includes basic fields like first name, last name, OK, and Cancel. Seems simple enough, right?
However, one of the key rules in place is that duplicate employees cannot be submitted. To address this rule, I have integrated an angular directive as follows:
(function() {
'use strict';
angular.module('app').directive('checkDuplicateEmployee', ['$q', 'officesSvc', 'webDataSvc', directive]);
function directive($q, officesSvc, webDataSvc) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, vm) {
vm.$asyncValidators.duplicateEmployee = function (modelValue, viewValue) {
// Issue detected here!
var args = {
officeType: officesSvc.officeType,
officeName: officesSvc.selectedOffice.name,
firstName: scope.vm.firstName,
lastName: scope.vm.lastName
};
// Custom $http wrapper.
return webDataSvc.get('/api/admin/DoesEmployeeExist', args)
.then(function(results) {
if (results === true)
deferred.reject(results);
return true;
});
};
}
}
}
})();
The problem arises when I apply the directive to an input field...
<input type="text" id="firstName" name="firstName"
maxlength="35"
ng-model="vm.firstName"
required check-duplicate-employee />
After entering text, what gets sent to the server is actually the state before my most recent keystroke.
Field: | vm.firstName:
----------------------------
T |
Te | T
Tes | Te
Test | Tes
This situation reveals that the scope doesn't update until after the validation process occurs.
My Question: Is there a way to perform asynchronous validation after the $scope.vm
object has fully updated? Keep in mind, simply passing the viewValue
to the firstName
property in the arguments list isn't a feasible option due to having the same validation process on both the vm.firstName
and vm.lastName
properties!