I'd like to do a traditional form submit from within a controller. The scenario is that I want to hit a route on my web server and redirect to its response, which I can do with a regular form in HTML, but I also want to do some validation on its fields when the submit button is pressed, and if the validation fails, I don't want to do the route.
I'm aware of ng-valid, but I only want the validation to take place when the button is hit.
Is there a way to conditionally do a form submit from within a controller?
The submit event fires when the user clicks a submit button ( <button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form. submit() method directly.
A form controller is triggered either upon the form's submission or on adding or updating input in a form field. When a user adds or updates an input value in a form field or clicks the submit or cancel button in the form, the form function associated with this function is triggered to execute the intended action.
You can add submit method to a FormController. I did so:
<form ng-form-commit action="/" name='payForm' method="post" target="_top">
<input type="hidden" name="currency_code" value="USD">
<button type='button' ng-click='save(payForm)'>buy</button>
</form>
.directive("ngFormCommit", [function(){
return {
require:"form",
link: function($scope, $el, $attr, $form) {
$form.commit = function() {
$el[0].submit();
};
}
};
}])
.controller("AwesomeCtrl", ["$scope", function($scope){
$scope.save = function($form) {
if ($form.$valid) {
$form.commit();
}
};
}])
Did you try to use the ng-submit directive on your form? You may return true/false after your validation.
Controller
app.controller('MainCtrl', ['$location', function($scope, $location) {
$scope.submit = function(user) {
var isvalid = true;
// validation
if (isvalid) {
$http.get('api/check_something', {}).then(function(result) {
$location.path(result.data);
});
return true;
}
return false; //failed
}
});
Html (you must not have an action attribute)
<form name="formuser" ng-submit="submit(user)">
<input type="text" ng-model="user.firstname" />
<input type="text" ng-model="user.lastname" />
<button type="submit">Submit</button>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With