Mik*_*ras 32 forms submit angularjs
我想在控制器内做一个传统的表单提交.场景是我想在我的网络服务器上点击一条路线并重定向到它的响应,我可以用HTML中的常规表单来做,但我也希望在按下提交按钮时对其字段进行一些验证,并且如果验证失败,我不想做路线.
我知道ng-valid,但我只想在按下按钮时进行验证.
有没有办法从控制器内有条件地提交表单?
小智 34
您可以将提交方法添加到FormController.我这样做了:
<form ng-form-commit action="/" name='payForm' method="post" target="_top">
<input type="hidden" name="currency_code" value="USD">
<button type='button' ng-click='save(payForm)'>buy</button>
</form>
.directive("ngFormCommit", [function(){
return {
require:"form",
link: function($scope, $el, $attr, $form) {
$form.commit = function() {
$el[0].submit();
};
}
};
}])
.controller("AwesomeCtrl", ["$scope", function($scope){
$scope.save = function($form) {
if ($form.$valid) {
$form.commit();
}
};
}])
Run Code Online (Sandbox Code Playgroud)
您是否尝试在表单上使用ng-submit指令?您可以在验证后返回true/false.
调节器
app.controller('MainCtrl', ['$location', function($scope, $location) {
$scope.submit = function(user) {
var isvalid = true;
// validation
if (isvalid) {
$http.get('api/check_something', {}).then(function(result) {
$location.path(result.data);
});
return true;
}
return false; //failed
}
});
Run Code Online (Sandbox Code Playgroud)
Html(你不能有一个动作属性)
<form name="formuser" ng-submit="submit(user)">
<input type="text" ng-model="user.firstname" />
<input type="text" ng-model="user.lastname" />
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)