angularjs自定义验证的实现

来源:互联网 发布:面向切面编程面试 编辑:程序博客网 时间:2024/05/18 04:43

1.先看代码

<form name="tform" novalidate><input name="val" type="text" ng-model="_val" ng-int required/><span ng-show="tform.val.$error.required" >信息不能为空</span><span ng-show="tform.val.$error.int" >int Error</span></form>

<script>var app = angular.module('app', []);app.controller('ctrl', function($scope) {});app.directive('ngInt', function() {return {restrict: 'AE',require: 'ngModel',link: function(scope, element, attrs,ctrl) {console.log(attrs);console.log(ctrl);ctrl.$setValidity('int',true);scope.$watch(attrs.ngModel,function(newValue) {console.log(newValue);if(isNaN(newValue)&&newValue!=undefined){ctrl.$setValidity('int',false);}
else {ctrl.$setValidity('int',true);}})}}})
2,代码解析:
directive用来自定义指令,在return中
require:require - 请求另外的controller,传入当前directive的link function中。require需要传入一个directive controller的名称。如果找不到这个名称对应的controller,那么将会抛出一个error。名称可以加入以下前缀:

? - 不要抛出异常。这使这个依赖变为一个可选项。

^ - 允许查找父元素的controller


link:链接函数负责将作用域和DOM进行链接。
scope, element, attrs,ctrl四个参数,
element简单说就是$("_val")
attrs指的当前ng-model所在的组件的所有的属性,比如说,name,type,ng-model这些;
ctrl指的是ng-model对象;

原创粉丝点击