对于我正在处理的项目,我有一个非常简单的对话框,可以将自定义员工添加到业务应用程序中。模态本身并没有什么特别之处——名字、姓氏、OK、Cancel。容易……对吧?
然而,其中一项业务规则是我们不允许提交重复的员工。为此,我实现了以下角度指令:
(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) {
// Problem visible here!
var args = {
officeType: officesSvc.officeType,
officeName: officesSvc.selectedOffice.name,
firstName: scope.vm.firstName,
lastName: scope.vm.lastName
};
// Custom wrapper for $http.
return webDataSvc.get('/api/admin/DoesEmployeeExist', args)
.then(function(results) {
if (results === true)
deferred.reject(results);
return true;
});
};
}
}
}
})();
我遇到的问题是,当我将指令添加到输入时......
<input type="text" id="firstName" name="firstName"
maxlength="35"
ng-model="vm.firstName"
required check-duplicate-employee />
我输入了一些东西,发送到服务器的状态是我按键之前的状态。
Field: | vm.firstName:
----------------------------
T |
Te | T
Tes | Te
Test | Tes
因此,我可以由此推断,直到验证运行之后,范围才会更新。
问题:如何在$scope.vm
对象更新后进行异步验证?请记住,我不能只将 传递viewValue
给firstName
args 列表中的属性 - 我对vm.firstName
和vm.lastName
属性的输入进行了相同的验证!