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.
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:This is the second cause of problems.
Hope this helps.