问题
I have a form that generates some fields using ng-repeat. I want to attach each independent field to set validity in case it is left empty. Is there a way to do this?
Thanks!
回答1:
You need to use ng-form
with your ng-repeat
. I'd update your example, but you didn't give me one... so the idea is something like this:
<form name="myForm">
<div ng-repeat="item in items" ng-form="repeatForm">
<input type="text" name="foo" ng-model="item.foo" required/>
<span ng-show="repeatForm.foo.$error.required">required</span>
</div>
</form>
If you needed to access 'setValidity' on the model for some reason, you'd probably have to pass repeatForm.foo
to a function either on your controller or on your scope. like ng-click="myWeirdValidationFunction(repeatForm.foo)"
. There's probably not much of a use case for this though.
来源:https://stackoverflow.com/questions/24290143/angularjs-setvalidity-in-ng-repeat-fields