0

I have 2 controllers: btnController and formController. I am trying to submit a Form from another controller action. The problem is that the function in the controller should only be called when the Form Validation is Valid. Right now, if the user tries to submit the form without writing anything, the submit function is called.

How can i fix it?

My code

<div ng-app='app'>
    <div class='header' ng-controller='btnController'>
        <button ng-click='submit()'>
            Submit Form
        </button>
    </div>

    <div class='container' ng-controller='formController'>
        <h2>Form</h2>
        <form id='myform'>
            <input ng-model='name' placeholder='name' required/>
            <span style="color:red" ng-show="myform.name.$dirty &&      myForm.name.$invalid">
                <span ng-show="myform.name.$error.required">Username is required.</span>
            </span>
        </form>
    </div>
</div>


(function(){
    var app=angular.module('app',[]);
    app.controller('btnController',function($scope){
        $scope.submit=function(){
            angular.element(document.getElementById('myform')).scope().submit();
        }
    });

    app.controller('formController',function($scope){
        scope.name;
        $scope.submit=function(){
            alert($scope.name);
        }
    });
})();

Here is the example JsFiddle

1 Answer 1

2

Edit:

The submit() function in your 'formController' will only be called when the form is valid:

app.controller('btnController',function($scope){
    $scope.submit=function(){
      var elementScope = angular.element(document.getElementById('myform')).scope();
      if(elementScope.myform.name.$valid)
         elementScope.submit();
    }
});

New Jsfiddle: https://jsfiddle.net/oucdodf8/

Sign up to request clarification or add additional context in comments.

8 Comments

that is not my problem. please look at the jsfiddle example
the submit call was from another controller and not in the form also.
So you want that the submit() function in your formController will ONLY be called when the form is valid, right?
Ya right. and also i want to show the validation error
ya i see that, but it doesn't show the required validation error. thank you
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.