Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I trigger a form submit from a controller?

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?

like image 381
Mike Pateras Avatar asked Apr 14 '13 19:04

Mike Pateras


People also ask

What triggers form submit?

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.

What is form controller?

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.


2 Answers

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();
     }
   };
}])
like image 170
ReklatsMasters Avatar answered Oct 23 '22 06:10

ReklatsMasters


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>
like image 8
jpmorin Avatar answered Oct 23 '22 05:10

jpmorin