AngularJS-验证后以编程方式提交表单



我最近开始在AngularJs 1.6。

我试图以编程方式提交表格。原因是我要验证一些字段(必需的字段验证)。我花了很多努力(大概3-4个小时)试图完成这项工作,但是堆栈溢出或Angularjs文档上的现有答案似乎都对我有用(奇怪)。

下面是我的html

<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
    <div>
        {{message}}
    </div>
    <div>
        <label>User Name</label>
        <input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" />
    </div>
    <div>
        <label>Password</label>
        <input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" />
    </div>
    <div>
        <input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" />
    </div>
</form>

我的角度代码

var demoApp = angular.module('demoApp', []);
demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {   
    $scope.loginUser = function () {
        var form = document.getElementById("loginform");
        //var form = $scope.loginform; - tried this here...
        //var form = $scope["#loginform"]; tried this
        //var form = angular.element(event.target); - tried this...
        // tried a lot of other combinations as well...
        form.attr("method", "post");
        form.attr("action", "Home/Index");
        form.append("UserName", $scope.user.UserName);
        form.append("Password", $scope.user.Password);
        form.append("RememberMe", false);
        form.submit();
    };
}]);

我继续获得错误'attr'不是函数。

我所需要的只是使用邮政方法提交表单,并带有值。在此之前,我正在尝试拦截提交电话并检查验证。

我也愿意尝试任何其他方法。例如将输入类型从submit更改为button。将输入放在表单外。如果验证并提交两者都可以发生任何方式,我会很高兴。我只希望它在验证客户端验证后将值发布,然后服务器将照顾重定向。

注意:我希望表格可以完成完整的后背,以便我可以将其重定向到另一个表单。(我知道我可以使用ajax,但有时可能是!)

所有的第一个避免执行var form = document.getElementById("loginform");。而不是使用form.submit,您可以使用以下代码。为此,角度的方式欢呼:D

$scope.loginUser = function () {
  if($scope.loginform.$valid){
      user.rememberme=false;
       $http({
         url: 'Home/Index',
         method: "POST",
         data: user 
    })
    .then(function(response) {
        // success
    }, 
     function(response) { // optional
        // failed
    });
  }
};

这是验证的代码,如果验证不启用按钮

<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
<div>
    {{message}}
</div>
<div>
    <label>User Name</label>
    <input type="text" id="txtUserName" required ng-model="user.UserName" name="UserName" />
</div>
<div>
    <label>Password</label>
    <input type="text" id="txtPassword" ng-model="Password" name="user.Password"required />
</div>
<div>
    <input type="submit"  ng-disabled="myForm.UserName.$invalid || myForm.Password.$invalid" id="btnLogin" title="Save" name="btnLogin" value="Login" />
</div>
</form>

尝试访问表单时应该使用$范围,例如 $scope.loginform。但......看看NG-Messages。这是使用您的表格使用ng-messages的一个例子:

<form id="loginform" name="loginform" ng-submit="loginUser()">
    <div>
        {{message}}
    </div>
    <div>
        <label>User Name</label>
        <input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" required/>
        <div class="help-block" ng-messages="loginform.txtUserName.$error" ng-show="loginform.txtUserName.$touched">
            <p ng-message="required">Username is required.</p>
        </div>
    </div>
    <div>
        <label>Password</label>
        <input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" required/>
        <div class="help-block" ng-messages="loginform.txtPassword.$error" ng-show="loginform.txtPassword.$touched">
            <p ng-message="required">Password is required.</p>
        </div>
    </div>
    <div>
        <input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" ng-click="loginUser()" />
    </div>
</form>

添加ngmessages:

var demoApp = angular.module('demoApp', ['ngMessages']);
demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {   
    $scope.loginUser = function () {
      if($scope.loginform.$valid){
        //Code to run before submitting (but not validation checks)
      } else{
         return false;
     }
    };
}]);

不要忘记在应用程序声明中包含ngmessages,并包括ngmessages.js脚本文件。请注意如何简单地使用HTML5验证器。

我发现了我正在寻找的东西。最后,我必须创建一个指令,然后提交。所以我将其作为一个整体答案发布。

我的html

<div ng-controller="homeController" ng-init="construct()">    
    <form method="post" action="Index" role="form" id="loginform" name="loginform" ng-form-commit novalidate class="ng-pristine ng-invalid ng-invalid-required">
        <div class="form-group">
            <label for="UserName">User ID</label>
            <input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
                   id="UserName" name="UserName" ng-model="user.UserName" type="text" value=""
                   ng-change="userNameValidation = user.UserName.length == 0">
            <span class="field-validation-error text-danger" ng-show="userNameValidation">The User ID field is required.</span>
        </div>
        <div class="form-group">
            <label for="Password">Password</label>
            <input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
                   id="Password" name="Password" ng-model="user.Password" type="password" value=""
                   ng-change="passwordValidation = user.Password.length == 0">
            <span class="field-validation-error text-danger" ng-show="passwordValidation">The Password field is required.</span>
        </div>
        <div>
            <input type="button" id="btnLogin" title="Login" name="btnLogin" value="Login" ng-click="validateUser(loginform)" />
        </div>
    </form>
</div>

在表单元素上查找 ng-form-commit 。这是我创建的指令。

我的角度代码

var demoApp = angular.module('demoApp', []);
demoApp.factory("commonService", function () {
    return {
        isNullOrEmptyOrUndefined: function (value) {
            return !value;
        }
    };
});
//This is the directive that helps posting the form back...
demoApp.directive("ngFormCommit", [function () {
    return {
        require: "form",
        link: function ($scope, $el, $attr, $form) {
            $form.commit = function () {
                $el[0].submit();
            };
        }
    };
}]);
demoApp.controller("homeController", ["$scope", "commonService", function ($scope, commonService) {
    $scope.construct = function construct() {
        $scope.user = { UserName: "", Password: "" };
    };
    $scope.userNameValidation = false;
    $scope.passwordValidation = false;
    $scope.isFormValid = false;
    $scope.validateUser = function ($form) {
        $scope.isFormValid = true;
        $scope.userNameValidation = commonService.isNullOrEmptyOrUndefined($scope.user.UserName);
        $scope.passwordValidation = commonService.isNullOrEmptyOrUndefined($scope.user.Password);
        $scope.isFormValid = !($scope.userNameValidation || $scope.passwordValidation);
        if ($scope.isFormValid === true) {
            $scope.loginUser($form);
        }
    };
    $scope.loginUser = function ($form) {
        $form.commit();
    };
}]);

我在这里找到了指令

使用Angular 1.5组件的示例。

(function(angular) {
  'use strict';
  function DemoFormCtrl($timeout, $sce) {
    var ctrl = this;
    this.$onInit = function() {
      this.url = $sce.trustAsResourceUrl(this.url);
      /*$timeout(function() {
        ctrl.form.$$element[0].submit();
      });*/
    };
    this.validate = function(ev) {
      console.log('Running validation.');
      if (!this.form) {
        return false;
      }
    };
  }
  angular.module('app', [])
    .component('demoForm', {
      template: `
      <p>To run this demo allow pop-ups from https://plnkr.co</p>
      <hr>
      <p>AngularJS - submit form programmatically after validation</p>
      <form name="$ctrl.form" method="get" target="blank" action="{{::$ctrl.url}}" novalidate
       ng-submit="$ctrl.validate($event)">
        <input type='hidden' name='q' ng-value='::$ctrl.value'>
        <input type='hidden' name='oq' ng-value='::$ctrl.value'>
        <input type="submit" value="submit...">
      </form>`,
      controller: DemoFormCtrl,
      bindings: {
        url: '<',
        value: '<'
      }
    });
})(window.angular);

https://plnkr.co/edit/rrrrruj6vlwrxpn3od9yajy?

最新更新