EricC
EricC

Reputation: 5870

Form naming and model naming recommendation

If I have a form like this

<form name="form" ng-submit="form.save()">
  <input type="text" name="name" ng-model="form.name">
  <button type="submit" ng-disabled="form.name.$pristine">Submit</button>
</form>

Here I have a form named "form", an input-field named "name" and a model named "form.name". Will the formname+fieldname ("form.name") be in conflict with the model name ("form.name") somehow? Is this bad naming practice? Or maybe this is perfectly OK and will give me no troubles?

Upvotes: 1

Views: 65

Answers (1)

ms87
ms87

Reputation: 17492

To be honest that's a terrible Idea, naming your form the same your model. When you declare a form in Angular, a form object by the name of the form will be created on the Scope of the view's controller. Having a model object named same as the form will result in in mixing up of the 2 objects, the form object created by angular has many fields and functions of it's own, why would you want to litter your model with that? If you try running the code you posted and placing a $watch on form, you will notice that the model value won't even be bond properly:

$scope.$watch("form", function (v) {
  console.log(v);
}, true);

results in:

$addControl: function (control) {
$dirty: true
$error: Object
$invalid: false
$name: "form"
$pristine: false
$removeControl: function (control) {
$setDirty: function () {
$setPristine: function () {
$setValidity: function (validationToken, isValid, control) {
$valid: true
name: "[object Object]john"

Solution: Just give your model and form different names :)

Upvotes: 4

Related Questions