javascriptangularjsangularjs-scope

How to check all fields are empty in Angularjs


How to check all fields in the submit form ng-submit="submit(field)" is empty in controller.js? They consists of few textboxes and one select field.

I would want an alert box to occur if all fields are empty and select option is not selected, instead of individual validation.


Solution

  • While it's not exactly what you're asking about, may be $pristine is what you want? It's a flag on the form indicating whether the form has ever been edited. If someone typed and then cleared out a field, $pristine would still be false, however.

    <form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
        <input ng-model="firstName" name="firstName" />
    
    </form>
    

    Then in your controller

    .controller('FormController', function($scope){
        $scope.doSubmit = function(){
            if($scope.myform.$pristine){}
        }
    })
    

    Alternatively, you can set all your fields to required="true" and use the $valid flag on the form in the same way as described above.