Reputation: 1951
I need to set ng-form as invalid in the start, as it is a later part of a wizard. The form contains a grid with elements. Each element has its own validation, but the issue is that when there are no elements the form shows as valid. I need to mark it as invalid for the start case when the number of rows is 0. How can one do it?
Upvotes: 11
Views: 43351
Reputation:
I think the following is a cleaner solution.
$scope.$watch('myForm', function (a, b) {
$scope.myForm.$setValidity('custom', false, window); // 'custom' validation key, binds window as form control
});
I like the $watch
better; Initially, I was going to check "if the form had been created yet", and only then set the validity.
But it seems it's not really needed, the form is created before the $watch is executed its initial time (so no change is called for the watch).
The $setValidity
seems to be part of the ngForm API (I found it in the form.js source code), and it's used by form controls themselves which both sets $valid and $invalid.
Upvotes: 7
Reputation: 1951
After some research the following code works fine for me. In the controller:
//Set the form as invalid for start.
$timeout(function(){
$scope.orderForm.productsForm.$invalid = true;
});
The timeout assures that we gain access to the form. They are not constructed on the first pass through controller so a timeout or watch is needed.
Then we mark form as invalid. A better way could be locating an input that we can mark as invalid using documented api $setValidity
on ngModelController, but in my use case there is no input yet so we do it in a dirty way.
One caveat is that when one sets this directly like above the corresponding $invalid === ! $valid invariant is broken, so be careful with this hack.
Upvotes: 20