1

I have seen different ways of implementing a form and its logic behind to interact with the controller, and I would like to know what is the best approach to follow.

Example:

<form name="myForm" ng-submit="submit(user)">
  username: <input name="username" ng-model="user.username">
  age: <input name="age" ng-model="user.age">
</form>

In that example, our submit() method in the controller would have 3 ways of extracting username and age from the form:

  • Use the $scope.myForm object. This object has also information related to form validation.
  • Use the $scope.user object.
  • Use the user variable passed to the submit() method.

So my question is, what is the best practice?

3 Answers 3

1

Let's have a look at the 3 approaches:

  1. $scope.myForm should be used for form validation purposes only. I usually disable the submit button by checking $scope.myForm.$invalid.

  2. $scope.user - It would limit the submit function to only use this variable and reduce its reusability. You also have the overhead of typing more - $scope part, for which I'm being pedantic.

  3. I like the third approach more as it increases the reusability of the submit function.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the user variable passed to the submit(user) is the best approach to follow.

Comments

0

Do not use $scope, bind everything to controller instead. This how it should look like:

<form name="$ctrl.myForm" ng-submit="$ctrl.submit()">
  username: <input name="username" ng-model="$ctrl.user.username">
  age: <input name="age" ng-model="$ctrl.user.age">
</form>

Passing $ctrl.user to submit for me makes no sense, but this is more matter of style.

P.S. For simple cases you do not need Form object in controller, thow when things become complicated you will find live without it very difficult. As a live example try to add async validation on some field, that should happen both on blur and form submit (if validation on blur was not finished yet)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.