我有2个控制器:btnController和formController。我正在尝试从另一个控制器操作提交表单。问题是只有在表单验证有效时才应调用控制器中的函数。现在,如果用户尝试提交表单而不写任何内容,则会调用submit函数。
我该如何解决?
我的代码
<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);
}
});
})();
以下是示例JsFiddle
答案 0 :(得分:2)
修改强>
只有在表单有效时才会调用'formController'中的submit()函数:
app.controller('btnController',function($scope){
$scope.submit=function(){
var elementScope = angular.element(document.getElementById('myform')).scope();
if(elementScope.myform.name.$valid)
elementScope.submit();
}
});
新 Jsfiddle :https://jsfiddle.net/oucdodf8/