简体   繁体   中英

How to submit a form in Angular

I have an html form that I am validating with an Angular controller. If the validation fails, I apply certain classes to the html. If it passes, I want to let the form submit itself. Although this seems very straightforward, I haven't found an easy way to do this. One method I have found uses the $scope.$broadcast function to tell the form to submit, however, I am using the Controller as Ctrl syntax so I would rather not use $scope . Is there anyway to submit a form from a controller?

My simplified HTML

<form ng-controller="LoginCtrl as login" ng-submit="login.validate()" method="post">
    <input ng-model="login.username" />
    <input ng-model="login.password" />
</form>

JS

var app = angular.module("app", []);

app.controller("LoginCtrl", ["$http", function($http) {
    this.username = "";
    this.password = "";
    this.validate = function() {
        //validate
        if (valid) {
            // somehow form.submit()
        }
    };
}]);

I am somewhat new to Angular so forgive me if this is an obvious quesion ;)

EDIT : I need to clarify that I am looking to avoid submitting the form with AJAX (ie $http.post ). Basically what I want is the controller equivalent of calling form.submit() .

USE CASE : Let me explain exactly what I am trying to do.

User arrives at login page
User enters credentials
User hits Submit
    Controller asks server (using api path) if the credentials are valid
    if valid then
        Tell the form to submit to regular login path // how?
    else
        Immediately tell the user they submitted invalid credentials

This way the User gets immediate feedback if they entered incorrect credentials. All of this I have implemented except for the actual form submission.

Simplest approach would be wrap all the form element data into one object. You don't have to create this object if you have no data to prepopulate, ng-model will create it for you.

<form ng-controller="LoginCtrl as login" ng-submit="login.validate()" method="post">
    <input ng-model="login.MyFormData.username" />
    <input ng-model="login.MyFormData.password" />
</form>

This will result in an object in your controller scope looking like:

$scope.MyFormData={
   username :'foo',
   password:'bar'
}

When ready to submit:

$http.post('path/to/server', $scope.myFormData).success(response){
   /* do something with response */
})

I think you want to have validation as part of your form submission flow. Try something like this:

HTML

<form ng-controller="LoginCtrl as login" ng-submit="login.submit()" method="post">
    <input ng-model="auth.username" />
    <input ng-model="auth.password" />
    <div class="error" ng-hide="valid">Something is invalid...</div>
</form>

JS

var app = angular.module("app", []);

app.controller("LoginCtrl", ["$http", "$scope", function($http, $scope) {
    $scope.valid = true;
    $scope.auth.username = "";
    $scope.auth.password = "";

    var valid = function() {
        // validate

        return valid; // true or false
    };

    this.submit = function() {
        if (valid()) {
            $http.post('/your/auth/url', { auth: auth }).success(function(response) {
                // whatever you're doing to store the auth response.
            });
        } else {
            // use this to conditionally show error messages with ng-show
            $scope.valid = false;
        }
    };
}]);

I'm not sure I understand your comment about using the controller-as syntax. That shouldn't change how you use $scope .

I have an example with the bare minimum code here . Note, it is self validating, and you don't even need to submit anything from the COntroller! you can include the action and method fields as form attributes, and angular will submit the form if it is valid

HTML

<form name="LoginCtrl as loginForm" method="Post" action="not-a-real-script.php">
  <input type="text" name="name" ng-model="loginData.name" placeholder="username" required="" />
  <input type="password" name="password" ng-model="loginData.password" placeholder="Password" required />
  <input type="submit" ng-disabled="loginForm.$invalid" value="Login" />
</form>

JS

angular.module('app', [])
.controller('LoginCtrl', function($scope) {
  $scope.loginData = {};
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM