jalv1039
jalv1039

Reputation: 1682

form best practices (angularjs 1.6)

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:

So my question is, what is the best practice?

Upvotes: 1

Views: 349

Answers (3)

Petr Averyanov
Petr Averyanov

Reputation: 9476

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)

Upvotes: 0

abhim
abhim

Reputation: 1186

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.

Upvotes: 1

Kalpesh
Kalpesh

Reputation: 63

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

Upvotes: 0

Related Questions