angular.js - AngularJS使用自訂的表單驗證指令後,輸入內容不提交?
phpcn_u1582
phpcn_u1582 2017-05-15 16:57:43
0
1
518

指令碼如下:

 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

全部回覆(1)
过去多啦不再A梦

你把指令中的 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);
    }

這是導致出現問題的第二個原因

希望可以幫助你。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!