所以我试图在验证后自动提交表单。
HTML
<form name="myForm" role="form" novalidate>
<div class="form-group">
<select class="form-control" name="location" ng-model='calc.location1' required>
<option value=7>Location1</option>
<option value=9>Location2</option>
<option value=5>Location3</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type='number' name="Size" ng-model='calc.Size' placeholder="Sq ft" required>
</div>
<div class="form-group">
<input class="form-control" type='number' name="units" ng-model='calc.units' placeholder="Units in kWH" required>
</div>
</form>
控制器
myapp.controller('demoController', ['$scope', function($scope, $document) {
$scope.$watch('myForm.units.$valid', function (newValue, oldvalue){
if(newValue) {
console.log(newValue);
}
})
}])
我想在if语句中插入表单提交代码,但即使表单输入在页面加载时为空,newValue也始终显示为true。
尝试做这样的事情http://jsfiddle.net/cmyworld/EdCEW/但不知道我哪里出错了。
答案 0 :(得分:0)
解决方案是创建一个方法来验证所有字段,如果所有字段都有效,则将范围变量设置为true。
var app = angular.module('myApp', []);
app.controller('myController',['$scope',function($scope) {
$scope.checked = 0;
$scope.$watch('myForm.$valid', function (newValue, oldvalue){
$scope.checkDirty();
if($scope.checked === 1)
{ alert('Model is valid');
//Can do a ajax model submit.
}
});
$scope.checkDirty = function(){
if($scope.myForm.Size.$valid && $scope.myForm.units.$valid)
{
$scope.checked = 1;
}
else
{
$scope.checked =0;
}
};
}]);