Angular, needs controller validation in many forms

I am trying to find a simple solution for the required input type. I have a couple of small forms that all submit to one button while keeping at the bottom of the page. What I am trying to accomplish is something like ngRequired, however across the whole controller, not just individual forms. So the desired effect is pretty simple - if any of the inputs are empty, set the boolean (or whatever) to false, which disables the save button at the bottom.

So my first attempt is like this:

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

then I have a function that checks when you try to click the button how much is thrown

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, do nothing (all the required ones are not filled)

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 it should be much easier than my first try. Maybe something similar to validating if any particular one of these required fields is false fails? I know ngRequied will be great for this, but unfortunately the way it should be structured it can't be one big shape. There should be a much easier way to accomplish this task: angular.

Any input would be greatly appreciated, thanks for reading!

+3


source to share


2 answers


You can use ng-form to nest multiple forms. It allows you to use nested forms and validate multiple forms as one form.

So, you need to nest 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 have to do is check the validation status of the parent form.

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

      

+2


source


you can use directive myForm.$invalid

as described here: Disable submit button if form is invalid using AngularJS



0


source







All Articles