angular.js - After AngularJS uses a custom form validation instruction, the input content is not submitted?
phpcn_u1582
phpcn_u1582 2017-05-15 16:57:43
0
1
588

The command code is as follows:

 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);
                    }
                });
            }
        }
    });

The html code is as follows:

<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>

Controller code:

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

The verification can be executed normally, that is, as long as I add the "ifHanzi" instruction I wrote, the submitted content of the form cannot be obtained in the controller and becomes undefined. Is my instruction written wrong or is there something else? If I haven't noticed anything, I hope the students can give me some pointers. Thank you.

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