user3454794
user3454794

Reputation: 15

angularjs form submit data empty

Good day to all.

Have a form element

<form name="myForm" ng-submit="subMe()">
  <input type="text" name="name" value="" />
</form>

and

$scope.subMe = function(){
  console.log( $scope.myForm ); // return empty object as {}
}

so, how I can see data in the form? There are many inputs elements will be in the future.

And is the best practice for check valid form in back-end? Do as some like:

var _valid = $http.post();
if ( _valid) {
  if ( createUserSuccess() ){
    showSucceess();
  } else {
    showError();
  }
} else {
  showBadFilledFormElements();
}

Thanks!

Upvotes: 1

Views: 5005

Answers (3)

cpk
cpk

Reputation: 809

You have no submit input or button, so ng-submit isn't what you would use to view the form data.

initialize an empty object in the scope of your form like so

myApp.controller('formController', function($scope) {
  $scope.formData = {};

  $scope.submitForm = function() {
      //do stuff on submit
  }
});

Then bind the ng-model in your markup like so

<div ng-controller="formController">
   <form name="myForm" ng-submit="submitForm()">
       <input type="text" name="name" ng-model="formData.name" value="" />
       <button type="submit">Submit</button> 
   </form>
    {{formData}}
</div>

You can view it with {{formData}} in the markup, within the scope of formController

EDIT: changed submit form function name to make more sense.

Upvotes: 2

stevemao
stevemao

Reputation: 1483

Eric Olson's answer is pretty much correct. I just want to add something here. You might wanna checkout ngForm

ngForm

Nestable alias of form directive. HTML does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.

Note: the purpose of ngForm is to group controls, but not to be a replacement for the tag with all of its capabilities (e.g. posting to the server, ...).

Upvotes: 1

Eric Olson
Eric Olson

Reputation: 2985

You need to add models to your form's input elements:

<form name="myForm" ng-submit="subMe()">
  <input type="text" name="name" value="" ng-model="myForm.name" />
  <input type="text" name="email" value="" ng-model="myForm.email" />
</form>

and

$scope.subMe = function(){
  console.log( $scope.myForm ); // { name: "abc", email: "[email protected]"}
}

I am not sure I understand the second part of your question, but you will want to create an Angular Service for best practices when submitting your form data to your api.

Upvotes: 0

Related Questions