我正在使用 Angular 制作一个注册表单,其中还包含一个用户名输入字段。我编写了一条指令,在字段模糊时在服务器端检查用户名的“唯一性”。
这是我的 Angular 代码:
App.directive('usernameCheck', ['$http', function ($http) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
elem.on('blur', function (evt) {
scope.$apply(function () {
$http({
method: 'POST',
url: '/usernameCheck/', <-- NEVER ACCESSED!?
data: {'username' : $scope.userName}
}).success(function(data, status, headers, config) {
ctrl.$setValidity('unique', data.status);
});
});
});
}
}
}]);
以及 HTML 表单输入元素:
<input type="text" class="form-control" ng-model="userName" name="userName" username-check required>
出于某种奇怪的原因,该指令似乎不起作用。没有发生 JS 错误,但模糊元素不会触发 - 根据 Firebug,服务器路由“/usernameCheck”永远不会被调用。我错过了什么?
最佳答案
尝试使用ng-blur
方法(简单的通用示例):
app.directive('directiveName', function () {
return {
restrict: 'E',
scope: {
ngBlur: '&'
},
link:function(scope){
scope.onBlur = function(ev){
console.log(ev);
}
},
template: '<input ng-blur="onBlur($event)"></input>'
}
});
关于javascript - AngularJS:模糊事件未在表单验证指令中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093139/