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 (i.e. $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.
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
JS
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.This will result in an object in your controller scope looking like:
When ready to submit:
I think you want to have validation as part of your form submission flow. Try something like this:
HTML
JS
I'm not sure I understand your comment about using the controller-as syntax. That shouldn't change how you use
$scope
.