3

I am trying to find a simple solution to a required input type of scenario. I have multiple small forms that all send on one button save on the bottom of the page. What I am trying to accomplish is something like ngRequired, however across the whole controller, not just the individual forms. So the desired effect is pretty simple - if any of the inputs aren't filled out - set a boolean( or something) to false that disables the save button at the bottom.

So my first attempt is like this -

I have a model on each of the required items - there are 10 items

then I have a function that checks when you try to click the button how many are chcked like this

if($scope.modeltracker1){
    //if there is anything inside model 1 add 1 to the tracker
    $scope.modeltracker += 1;
}

and if the counter is not 10, don't do anything (all required are not filled out)

if($scope.modeltracker != 10){
    //do nothing because all required are not filed out
}else{
    //run save, all required all filed out
 }

So - I feel like there should be a much easier solution than my first attempt here. Maybe something along the lines of checking if any individual one of these required fields is false, don't fire? I know that ngRequied would be great for this, but unfortunately the way this has to be structured, it cannot be one large form. There has to be a much easier way to accomplish this task with angular.

Any input would be much appreciated, thanks for reading!!

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133

2 Answers2

2

You can use ng-form to nest your multiple forms. It allows using nested forms and validating multiple forms as one form.

So, you need to nest your multiple forms in one root form.

<div ng-controller="demoController">
  <form name="parentForm">
    <ng-form name="firstForm">
      <input type="text" ng-model="firstModel" required>
    </ng-form>
    <ng-form name="secondForm">
      <input type="text" ng-model="secondModel" required>
    </ng-form>
  </form>
</div>

Then, all you need to do is to check parent form's validation status.

 angular.module('formDemo', [])
.controller('demoController', ['$scope', function($scope) {

 if($scope.parentForm.$valid) {
    //run save, all required all filed out
 } else {
   //do nothing because all required are not filed out
 }
}]);
halilb
  • 4,055
  • 1
  • 23
  • 31
0

you can use myForm.$invalid directive, as explained here: Disable submit button when form invalid with AngularJS

Community
  • 1
  • 1
Ivan Seidel
  • 2,394
  • 5
  • 32
  • 49