angular.js - AngularJS使用自定义的表单验证指令后,输入内容不提交?
phpcn_u1582
phpcn_u1582 2017-05-15 16:57:43
0
1
550

指令代码如下:

 var regex = /[\u4e00-\u9fa5\u3400-\u4db5\ue000-\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" class="form-control" ng-model="Input" name="inputText" if-hanzi>
        <button class="btn btn-primary" 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,是我的指令写错了还是有其他没有注意到的地方,希望同学们指点一下,谢谢啦。

phpcn_u1582
phpcn_u1582

reply all(1)
过去多啦不再A梦

Just remove the scope = true in the command. You are using an independent scope. The dormitory is disconnected and you have to use your mobile phone...


Update: 2015-12-13

1. First of all, because you require的是一个指令,即ngModel,而这个指令是没有隔离作用域的,如果你设置scope = true,那么就会导致内部ngModel无法更新外部ngModel的对应值。这个是导致上面问题的重点。所以去掉这个配置选项就可以了。
2.你给ngModel.$parsers传递的函数方法,在验证了ifHanzi did not return the result, which resulted in the value on the view not being passed to the model. It can be changed as follows:

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

This is the second cause of problems.

Hope this helps.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template