原创 

关于angularjs $asyncValidators $http的异步验证扩展踩过的那些坑

分类:    2018人阅读    IT小君  2016-03-03 13:35

情景:验证用户输入Email是否已注册,扩展$asyncValidators 
相关代码如下:
Html code:

<div class="form-group">
	<input type="email" name="email" class="col-md-12 taginput" placeholder="登录邮箱" asynverification ng-model="RegIfo.Email" required>
	<span ng-show=\' myForm.email.$invalid&&myForm.email.$dirty\' >邮箱信息错误。</span>
	<span ng-show="myForm.email.$pending.asynverification">正在检测邮箱是否已注册...</span>
	<span ng-show="myForm.email.$error.asynverification">邮箱已注册,请更换邮箱!</span>
</div>


最终可用扩展代码:
ITClubApp.directive(\'asynverification\', function($http, $q) {
	  return {
	    require: \'ngModel\',
	    link: function(scope, elm, attrs, ctrl) {
	      ctrl.$asyncValidators.asynverification = function(modelValue, viewValue) {
	        var type =attrs.asynverification;
	        return $http({method: \'GET\', url:config.DomainPrefix+\'/user/IsRegistered?email=\'+modelValue})
				 .then(function(response){
					 if(response.data){
						 return $q.reject(response.data);
					 }else{
						 return response.data;
					 }
				});
	      };
	    }
	  };
	});


问题(那些坑):
1、关于angularjs $Http post在Spring后台接收不到值的问题,请移步 http://my.oschina.net/tommyfok/blog/287748,
我放弃了post改用get后台使用gson获取对象。
2、直接调用$http时(没有返回)$asyncValidators报异常,所以添加  return $http、return $q.reject(response.data)、return response.data
3、处理结果无法填充到变量即:myForm.email.$error.asynverification没有值,所以添加了$q(关于$q请看4),并在返回结果中添加return $q.reject(response.data),返回return response.data时myForm.email.$error.asynverification是没有值的,即默认为false.
4、$q是一个angularjs服务(官方说明如下引文),保证、承诺(保证后他就返回了你可以处理其他的,但他回去处理)一个异步事件的完成,详见:http://docs.ngnice.com/api/ng/service/$q
reference:
The CommonJS Promise proposal describes a promise as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.

以上讲解不够详尽若有大神路过请不吝赐教


支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»