Aviel Fedida
Aviel Fedida

Reputation: 4102

AngularJS, Module object and form name

I having trouble to understand some weird problem, I will explain as sort as i can:

For example i got this form:

<form method="post" action="index.htm" name="chat" novalidate>
        <label ng-show="chat.message.$error.pattern || chat.message.$error.required" for="message">Some error message</label>
        <textarea ng-required="true" type="text" maxlength="200" id="message" name="message" ng-pattern="patterns.chatMessage" ng-model="chat.message"></textarea>
        <input type="submit" value="send" ng-disabled="chat.$invalid">
</form>

Please note(because i didn't included all the code) that ng-pattern="patterns.chatMessage" patterns is a $rootScope property.

So when the page load i was expecting chat.message.$error.pattern to be false, But apparently unless i will set ng-model="some other object like client.message" or set ng-model="some other object property like chat.comment" When the page load chat.message.$error.pattern will be true, So basically if the model object.property is the same as the formName.textareaName i got this wierd problem.

In sort what is happen is that chat.message.$error.pattern is set to true from the moment the page load, If anyone can please explain what is the problem here i will be very thankful, Thank you all and have a nice day.

Upvotes: 0

Views: 73

Answers (1)

Stewie
Stewie

Reputation: 60406

You cannot use the same scope variable in form's name tag and in your ng-model.

When you use a form tag in angular, and that tag has a name attribute (e.g. chat), the Angular will create an instance of ngFormController on current scope and will assign that instance to a variable as specified in name attribute (in this case chat).

If you use this very same scope variable chat to host your ng-model than your ngFormController (defined on $scope.chat) will become overwritten by your model and it will produce erratic results.

So, to fix things, you need to rename your form:

<form method="post" action="index.htm" name="chatForm" novalidate>
  <label ng-show="chatForm.message.$error.pattern || chatForm.message.$error.required" for="message">Some error message</label>
  <textarea ng-required="true" type="text" maxlength="200" id="message" name="message" ng-pattern="patterns.chatMessage" ng-model="chat.message"></textarea>
  <input type="submit" value="send" ng-disabled="chatForm.$invalid">
</form>

Upvotes: 1

Related Questions