我的注册表格带有文本框用户名。我想要做的是当用户输入用户名时,custom指令将检查输入的用户名是否存在于数据库中。
所以这是我的api:
/*get the unique username*/
$app->get('/checkUsers', function ($id=null) {
$status_code = 200;
$resp = array('status'=>'success','message'=>'Query Success','data'=>null);
$resp['data'] = $id ? User::find(username) : User::find_all_by_active('1');
if(is_object($resp['data'])){
$resp['data'] = $resp['data']->to_array();
}else{
$resp['data'] = objToArr($resp['data']);
}
JSONResponse($status_code,$resp);
});
这是我的指令.js
'use strict';
angular.module('installApp')
.directive('ngUnique', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, elem, attrs, ctrl) {
// check that a valid api end point is provided
if (typeof attrs.isUniqueApi === "undefined" || attrs.isUniqueApi === ""){
throw new Error("Missing api end point; use is-unique-api to define the end point");
}
// set a watch on the value of the field
scope.$watch(function () {
return ctrl.$modelValue;
}, function(currentValue) {
// when the field value changes
// send an xhr request to determine if the value is available
var url = attrs.isUniqueApi;
if (typeof currentValue !== 'undefined') {
url += "?val=" + currentValue;
elem.addClass('loading');
$http.get('url').success(function(data) {
elem.removeClass('loading');
ctrl.$setValidity('unique', data.isAvailable);
}).error(function() {
elem.removeClass('loading');
});
}
});
}
};
});
我的view.html:
<input type="email" ng-model="email" name="email" is-unique is-unique-api="../api/v1/checkUsers"/>
<p ng-show="newAccount.email.$dirty && newAccount.email.$invalid">
<span id="unique" ng-show="newAccount.email.$error.unique">Email already exists.</span>
</p>
到目前为止,我指的是https://github.com/brunoscopelliti/ng-unique。但它对我不起作用,请帮忙! :' - (谢谢
答案 0 :(得分:5)
为此目的存在异步验证器 - 请参阅ngModelController中的$ asyncValidators属性(https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
请注意,此功能来自版本1.3。