Leon Leon - 1 year ago 108
AngularJS Question

Angular - Use form post values in controller

I'm writing my first application in AngularJS, and I'm new to javascript. I have a simple question:

How do I use POST values from an html form in an angular controller?

I have a form (i've stripped out the css and validation stuff for ease of reading):

<form name="signupForm" novalidate>

<input type="text" placeholder="Name..." ng-model="name" name="name" required />

<input type="email" name="email" ng-model="email" placeholder="Email..." required>

<input type="password" placeholder="Password..." ng-model="password" name="password" required ng-minlength="7" ng-maxlength="50"/>

<button type="button" ng-click="auth.signup()">Sign Up</button>


I have a controller (no errors), with a function which looks a bit like this:

function SignupController($http, $scope, $rootScope, $location) {

vm.signup = function(name, email, password, onSuccess, onError) {

name: name,
email: email,
password: password
}).then(function(response) {
// etc

Now, how do I assign the values name, email, password from the form to name, email, password in the controller?


Answer Source

When you set the input with ng-model="email", then you can access those variable values in controller by just calling $scope.email.

Case-1: For single value


<input type="text" ng-model="email" />

Angular Controller


Case-2: For multiple values


<input type="text" ng-model="user.firstname" />
<input type="text" ng-model="user.lastname" />
<input type="text" ng-model="user.email" />

Angular Controller

//This will print the all the values (firstname, lastname, email) contains user as object.

Please check this working snippet to see the real time example

var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
  $scope.user = {};
  $scope.signup = function(){
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <form name="signupForm" ng-controller="FormCtrl" ng-submit="signup()">
  <input type="text" placeholder="Name..." ng-model="user.name" name="name" required />
  <input type="email" name="email" ng-model="user.email" placeholder="Email..." required>
  <input type="password" placeholder="Password..." ng-model="user.password" name="password" required ng-minlength="7" ng-maxlength="50"/>
  <button type="submit">Sign Up</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download