我需要在页面上显示两个必填字段。我有一个datePattern和必要的字段检查。
我需要在提交时显示字段而不输入字段。如果我输入的东西,我的datePattern工作正常。因为当我显示
时需要它Ng-show = Form.field1。$ error.required&& Form.field1 $质朴。这会在启动时显示所需的消息,但我想在提交时进行此操作,一旦我编辑了我的字段,datePattern进入图片就可以了。
我试过ng-click = submitted = true。并且ng-submit = ctrl.submit()它没有进入控制器..
有人能帮忙......
答案 0 :(得分:1)
我这样固定
表格。$ submit&& form.field1。$ error.required&& !form.field1。$感动
答案 1 :(得分:0)
<form ng-submit="validateForm()">
<input ng-model="name">
<span ng-show="invalidName">Please fill name field</span>
</form>
controller('MyController', function ($scope){
$scope.validateForm = function(){
if($scope.name){
$scope.invalidName = true;
}
if($scope.invalidName){
//Prevent submit
return false;
}else{
//Handle submit here or do nothing for auto submit of form
}
};
});
答案 2 :(得分:0)
我处理这种方式(没有承诺这是最好的方法)是在提交功能上我将每个表单字段设置为$ touch,然后对于每个字段,当字段为$ error和$ touch时我会显示警告
HTML
<div ng-app="app" ng-controller="ctrl">
<div ng-form="forms.datesForm">
<input type="text" ng-model="date" name=date required />
<p ng-show="forms.datesForm.date.$touched && forms.datesForm.date.$invalid">Please select a date.</p>
<br />
Your date: {{date}}
<button ng-click="submitForm()">Submit</button>
</div>
<p ng-show="submitted">
Congrats, you submitted successfully!
</p>
</div>
JS
angular.module('app', []);
angular.module('app').controller('ctrl', ['$scope', function ($scope) {
$scope.forms = {};
$scope.submitForm = function() {
if ($scope.forms.datesForm.$invalid) {
setAllFieldsTouched($scope.forms.datesForm);
return;
}
else {
// do whatever submit logic here
$scope.submitted = true;
}
}
var setAllFieldsTouched = function () {
// loop through all the empty required fields
angular.forEach($scope.forms.datesForm.$error.required, function (field) {
// only forms have $submitted properties, not fields
if (field.hasOwnProperty('$submitted')) { // is a form, recur through it
setAllFieldsTouched(field);
}
else { // this is a field
field.$setTouched();
}
});
}
}]);