Reputation: 10538
I was just wondering why I have to specify both name
and ng-model
on an input element in a form to be able to actually use it correctly.
For example, with the following:
<form name='test'>
<div>
<input type='radio'
value='create-new'
ng-model='toggle'
required />
<input type='radio'
value='use-existing'
ng-model='toggle'
required />
</div>
<div ng-switch='test.$invalid'>
<div ng-switch-when='true'>Invalid!</div>
<div ng-switch-when='false'>Valid!</div>
</div>
</form>
I would get the output Invalid!
when I don't select a radio button - this is correct behaviour. However, the downside is that the only way I can access this model is through $scope.toggle
- the element itself will not be referencable by name inside of $scope.test
(the form container). $scope.test
will contain the validation rules for toggle
, but it will not have any way of letting you know that those validation rules are belonging to toggle
as the name is not present.
If we were to switch it around put a name attribute on the input:
<form name='test'>
<div>
<input type='radio'
value='create-new'
name='toggle'
required />
<input type='radio'
value='use-existing'
name='toggle'
required />
</div>
<div ng-switch='test.$invalid'>
<div ng-switch-when='true'>Invalid!</div>
<div ng-switch-when='false'>Valid!</div>
</div>
</form>
Then our ng-switch
at the bottom will always show Valid, even though I've mentioned that the input itself is required. In addition, toggle
now shows up inside of $scope.test
, so I can check the validity of $scope.test.toggle
elsewhere (without requiring an inline attribute on that element).
If I combine both approaches and use both name
and ng-model
, then both results are combined and I get the result I would have expected - I can see $scope.test.toggle
and the model itself is validating correctly.
My question is why is this the appropriate behaviour? It seems different to, say, jquery.validate.unobtrusive
, where the name
attribute is the bit that intrinsically ties the validation rules to the element.
Upvotes: 12
Views: 3622
Reputation: 6720
name
attribute is used for angular validation, ng-model
for binding,
if you are not going to validate with angular you don’t have to use name
if you are not binding then don’t use ng-model
both are necessary if you need to validate in client side with angular and need binding
Upvotes: 21