Ryan Tran
Ryan Tran

Reputation: 487

Can not prevent submit form in angular js ?

I try many solutions to prevent my form submit after validataion by using

ng-submit="login_form.$valid"

But it still submit. This is my code. http://codepen.io/ryantran/pen/bgWXjy

Upvotes: 0

Views: 62

Answers (2)

vikas
vikas

Reputation: 1010

ng-submit takes a function to call, when you click on submit button. the way you are using will not work. To make it work, you can use it like:

  <form name="loginForm" novalidate ng-submit="loginForm.$valid ? login() : ''">

Using loginForm.$valid ? login() : ''" this condition makes sure that your function will only be called when form is valid.

And in controller:

 $scope.login = function () {
    if ($scope.loginForm.$valid) { //don't need to check validation here again because condition in ng-submit is doing this for you, only to show.
    authService.login(params).then(function(response) {
          //do what ever you want to, with you response
        }, function(error) {
           // do something
            }
        });
    }

make your all http request in service. Make sure $http is injected. In authService make function like below:

this.login = function (params) {
        return $http({
            method: "POST",
            url: serviceURI.loginURI,
            data: params,
            headers: { 'Content-Type': 'application/json' }
        });
    };

serviceURI is where i save all api urls as a constant.

Upvotes: -1

Yaser
Yaser

Reputation: 5719

Because you have defined action and method on your form, no matter what you do in angular it will submit.

If you want to handle the validation with angular you have to remove those and use $http or $resource to make your server call in your submit method.

Upvotes: 6

Related Questions