Reputation: 393
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
Upvotes: 0
Views: 1003
Reputation: 765
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/
Upvotes: 2