angular.js - AngularJS使用自定义的表单验证指令后,输入内容不提交?

浏览:61日期:2023-01-22

问题描述

指令代码如下:

var regex = /[u4e00-u9fa5u3400-u4db5ue000-uf8ff]/; app.directive('ifHanzi', function () {return { restrict: 'A', scope:true, require: 'ngModel', link: function (scope, ele, attrs, ngModelController) {ngModelController.$parsers.unshift(function (input) { if (regex.test(input)) {ngModelController.$setValidity(’ifHanzi’, true); } else {ngModelController.$setValidity(’ifHanzi’, false); }}); }} });

html代码如下:

<form name='iForm' ng-submit='Search(Input)'> <p class='input-group'><input type='text' ng-model='Input' name='inputText' if-hanzi><button type='submit>查询</button> </p> <span ng-show='iForm.inputText.$error.ifHanzi'>提示:只能输入汉字进行查询!</span></form>

控制器代码:

app.controller(’testCtrl’,[’$scope’,function($scope){ $scope.Search=function(Input){console.log(Input);//使用了表单验证指令后,Input就成了undefined }}]);

验证是可以正常执行的,就是只要添加了自己写的这个“ifHanzi”指令,表单的提交内容在控制器中就拿不到,成了undefined,是我的指令写错了还是有其他没有注意到的地方,希望同学们指点一下,谢谢啦。

问题解答

回答1:

你把指令中的 scope = true 去掉就好了,你使用了独立作用域,宿舍断网了,只好用手机了…

更新:2015-12-13

1.首先因为你require的是一个指令,即ngModel,而这个指令是没有隔离作用域的,如果你设置scope = true,那么就会导致内部ngModel无法更新外部ngModel的对应值。这个是导致上面问题的重点。所以去掉这个配置选项就可以了。2.你给ngModel.$parsers传递的函数方法,在验证了ifHanzi之后并没有将结果返回,这就导致了视图上面的值,最终没能够传递到模型上面去。可以改动如下:

if (regex.test(input)) {ngModelController.$setValidity(’ifHanzi’, true);return input; /* return the input */ } else {ngModelController.$setValidity(’ifHanzi’, false); }

这是导致出现问题的第二个原因

希望可以帮到你。

相关文章: