简体   繁体   English

如何在Angular中提交表单

[英]How to submit a form in Angular

I have an html form that I am validating with an Angular controller. 我有一个用Angular控制器验证的html表单。 If the validation fails, I apply certain classes to the html. 如果验证失败,则将某些类应用于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 . 我发现的一种方法使用$scope.$broadcast函数告诉表单提交,但是,我将Controller as Ctrl语法,所以我宁愿不使用$scope Is there anyway to submit a form from a controller? 无论如何,有需要从控制者那里提交表格吗?

My simplified HTML 我的简化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 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 ;) 我对Angular有点陌生,所以如果这是一个明显的疑问,请原谅我;)

EDIT : I need to clarify that I am looking to avoid submitting the form with AJAX (ie $http.post ). 编辑 :我需要澄清的是,我希望避免使用AJAX(即$http.post )提交表单。 Basically what I want is the controller equivalent of calling form.submit() . 基本上我想要的是等效于调用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. 如果没有要填充的数据,则不必创建此对象, ng-model会为您创建它。

<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 的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 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. 我不确定我是否理解您对使用controller-as语法的评论。 That shouldn't change how you use $scope . 那不应该改变$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! 注意,它是自我验证的,您甚至不需要从COntroller提交任何内容! you can include the action and method fields as form attributes, and angular will submit the form if it is valid 您可以将动作和方法字段包括为表单属性,如果有效,angular将提交表单

HTML 的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 JS

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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