How to check that all fields are empty in angularjs

How to check all fields in the submit form is ng-submit="submit(field)"empty in controller.js? They consist of several text fields and one selection field.

I would like the warning window to appear if all the fields are empty and the selection option is not selected, rather than a separate check.

thank

+4
source share
4 answers

Although this is not quite what you are asking, maybe $pristineit is what you want? This is a flag on the form indicating whether the form has ever been edited. If someone typed and then cleared the field, $pristineit would still be false.

<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){}
    }
})

required="true" $valid , .

+4

:

ng-show="!yourfield.length"

- :

<form name="yourform">
  <input name="yourfield" ng-model="somefield" ng-minlength="10" required>
  <span ng-show="!yourfield.myfield.$error.required">Something</span>
</form> 
0

You should look for form validation . Take a look at the tutorial .

<input name="name" class="form-control"
    ng-model="user.name" placeholder="Name" required>
  <div class="alert alert-danger"
    ng-show="userForm.name.$error.required">
    Please enter the name.
  </div>
0
source

A warning is shown below if all fields are empty.

angular.module('app', [])
.controller('FormController', function($scope) {
  $scope.doSubmit = function(){
    if (formIsEmpty($scope.myform)){
      alert('You forgot to enter something before submitting');
    }
  };
  
  function formIsEmpty(form) {
    for (var prop in form) {
      if (!form.hasOwnProperty(prop)) { continue; }
      if (prop[0] === '$') { continue; }
      if ($scope[prop]) { return false; }
    }
    return true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
    <input ng-model="firstName" name="firstName" />
    <input ng-model="lastName" name="lastName" />
    <textarea ng-model="description" name="description"></textarea>
    <button type="submit">Submit</button>
  </form>
</div>
Run codeHide result
0
source

All Articles