我不知道你为什么决定使用 angular-ui 而不是创建简单的指令,但我想可以keyup
在指令中添加事件ui-event
并调用函数来设置有效性true
。
但我宁愿建议您使用自定义指令保持简单:
yourApp.directive('checker', function () {
return {
restrict: 'A',
scope: {
checkValidity: '=checkValidity' // isolate directive's scope and inherit only checking function from parent's one
},
require: 'ngModel', // controller to be passed into directive linking function
link: function (scope, elem, attr, ctrl) {
var yourFieldName = elem.attr('name');
// check validity on field blur
elem.bind('blur', function () {
scope.checkValidity(elem.val(), function (res) {
if (res.valid) {
ctrl.$setValidity(yourFieldName, true);
} else {
ctrl.$setValidity(yourFieldName, false);
}
});
});
// set "valid" by default on typing
elem.bind('keyup', function () {
ctrl.$setValidity(yourFieldName, true);
});
}
};
});
和你的元素:
<input name="yourFieldName" checker="scope.checkValidity" ng-model="model.name" ng-required=... etc>
和控制器的检查器本身:
function YourFormController ($scope, $http) {
...
$scope.checkValidity = function (fieldValue, callback) {
$http.post('/yourUrl', { data: fieldValue }).success(function (res) {
return callback(res);
});
};
...
}