简体   繁体   中英

Angular auto form submit on validate with $watch

So I am trying to auto submit the form once it has been validated.

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>

Controller

myapp.controller('demoController', ['$scope', function($scope, $document) {
    $scope.$watch('myForm.units.$valid', function (newValue, oldvalue){
        if(newValue) {
            console.log(newValue);
        }
    })    
}])

I want to insert my form submit code inside the if statement, but newValue is always showing true even when the form inputs are empty at page load.

Trying to do something like this http://jsfiddle.net/cmyworld/EdCEW/ but no idea where I am going wrong.

The Solution is to create one method to validate all fields and set scope variable to true if all fields are valid.

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

Here is the example http://jsfiddle.net/EdCEW/92/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM