I have a simple form that looks like this:
<form name="myForm">
<input name="field" ng-model="item.field"></input>
<button ng-click="save()">Save</button>
</form>
In theory, I should be able to change things like validity of fields in the controller based on the form and field, as such:
$scope.save = function(item) {
item.$save();
$scope.myForm.field.$setValidity("some-error",false);
};
The problem is that directives at various levels get in the way and may set up multiple child scopes. So while item.field
is properly rendered and linked, my ability to do anything from the controller is very limited, e.g. if I wrap my partial in a fancy "loading" directive that hides it and shows "loading" until done.
<loading>
<form name="myForm">
<input name="field" ng-model="item.field"></input>
<button ng-click="save()">Save</button>
</form>
</loading>
Now my controller that wanted to directly set validity no longer has access to $scope.myForm
. Truth is, with possible directives, it never can safely rely on access to $scope.myForm
; only a directive can!
@Beyers recommends passing the form as part of the save()
call, as <button ng-click="save(myForm)">Save</button>
, which definitely works, but gets cumbersome.
Is there a real Angular way to do this cleanly? Should I be resetting to $pristine
inside my controller directly, or is there some other thing to do?
UPDATE:
I am beginning to wonder if this is the right approach at all. Should my controller be doing this like $setValidity
on a form? Shouldn't it take input from the view and modify business objects (item
) on that basis, as well as interact with services? How does angular know to reset ng-dirty
or ng-invalid
for its own validations?