Getting form controls from FormController

For a direct solution to the question, modify @lombardo’s answer like so;

     var dirtyFormControls = [];
     var myForm = $scope.myForm;
     angular.forEach(myForm, function(value, key) {
         if (typeof value === 'object' && value.hasOwnProperty('$modelValue') && value.$dirty)
             dirtyFormControls.push(value)                        
     });

The array ‘dirtyFormControls’ will then contain the form controls that are dirty.

You can also use this trick to show error messages on form submission for ‘Required’ validations and all others. In your submit() function you will do something like;

 if (form.$invalid) {
     form.$setDirty();              
     angular.forEach(form, function(value, key) {
         if (typeof value === 'object' && value.hasOwnProperty('$modelValue'))
             value.$setDirty();                        
     });
    //show user error summary at top of form.
     $('html, body').animate({
         scrollTop: $("#myForm").offset().top
     }, 1000);
     return;
 }

And in your form you will show error messages with

    <span ng-messages="myForm['subject-' + $index].$error" ng-show="myForm['subject-' + $index].$dirty" class="has-error">
        <span ng-message="required">Course subject is required.</span>
    </span>

The above solution is useful when you have dynamically generated controls using ‘ng-repeat’ or something similar.

Leave a Comment