I am faced with a dilemma involving two controllers: btnController and formController. Specifically, I need to submit a Form from another controller action while ensuring that the function in the controller is only called when the Form Validation is Valid. Currently, if a user attempts to submit the form without entering any information, the submit function is still triggered.
How can this issue be resolved?
Below is my code snippet:
<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);
}
});
})();
Feel free to check out the example on JsFiddle