原创  angularjs验证学习,问题及思考篇(angularjs validation)

分类: 2016-03-05T12:11:46    1077人阅读   
1、angularjs中提供了基本的验证, 验证在输入改变时触发(不是blur时),
验证完成后会给被验证标签添加样式(如:.ng-invalid),
验证时需要一个表单标签form包裹,但不是必须的

举个例子:

    

		<!DOCTYPE html>
		<html>
		<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
		<body ng-app="">
		<p>Try writing in the input field:</p>
		<form name="myForm">
		<input name="myInput" ng-model="myInput"  ng-maxlength="2">
		<span ng-show='myForm.myInput.$invalid' >最长2位。</span>
		</form>
		</body>
		</html>


以上验证长度不能超过2位,更多示例,请看这里:http://www.w3schools.com/angular/angular_validation.asp

2、问题
    a、不想使用Form标签,你可以使用ng-form,例如可将上述代码的form片段修改如下(div替换form):
         

	<div ng-form="myForm">
	<input name="myInput" ng-model="myInput"  ng-maxlength="2">
	<span ng-show='myForm.myInput.$invalid' >最长2位。</span>
	</div>

    b、如何修改验证在blur事件触发?

        答案一:使用angularjs内部的支持,在标签中加上属性 ng-model-options="{ updateOn: 'blur' }" 详见...

                    相关信息:
                         

            Angular 1.3 now has ng-model-options, and you can set the option to { 'updateOn': 'blur'} for example, and you can even debounce, when the use is either typing too             fast, or you want to save a few expensive DOM operations (like a model writing to multiple DOM places and you don't want a $digest cycle happening on every key                 down)

https://docs.angularjs.org/guide/forms#custom-triggers and https://docs.angularjs.org/guide/forms#non-immediate-debounced-model-updates

By default, any change to the content will trigger a model update and form validation. You can override this behavior using the ngModelOptions directive to bind only to specified list of events. I.e. ng-model-options="{ updateOn: 'blur' }" will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. ng-model-options="{ updateOn: 'mousedown blur' }"


       答案二:是指令,直接上代码:
        
     ITClubApp.directive('ngModel', function() {
		return {
			require: 'ngModel',
			link: function(scope, elem, attr, ngModel) {
				elem.on('blur', function() {
					ngModel.$dirty = true;
					scope.$apply();
				});

				ngModel.$viewChangeListeners.push(function() {
					ngModel.$dirty = false;
				});

				scope.$on('$destroy', function() {
					elem.off('blur');
				});
			}
		}
	});

以上代码不会有任何副作用,使用时验证使用方式不用任何修改,这段代码相当于重写了原有的触发时机代码。

将itclubapp改成你自己的application就可以用了。

3、在controller中获取验证结果
原理:通过提交时间将表单对象传递过去获取$vaild变量,看代码如下:

	<div class="form-group">
		<button type="button" class=" col-md-12 btn btn-success" ng-click="Registerfun(myForm)">注册</button>
	</div>
controller代码:


	$scope.Registerfun = function(form){
		if(form.$valid)
		{
			dosomething...
		}	
	}


讨论请留言


分享到: