不提交ng-submit

时间:2016-07-26 04:45:13

标签: angularjs

我需要在用户结账时从购物车中清除商品(localstorage)。

我只是想运行它,然后提交表单。

// clear the cart
shoppingCart.prototype.clearItems = function () {
    this.items = [];
    this.saveItems();
}

然而ng-click或ng-submit不会触发,它只是提交。 表格

<form novalidate action="http://localhost:8000/checkout" method="POST" 
ng-submit="submitCart()" class="form">
    <input class="btn btn-primary btn-flat" type="submit" ng-click="submitCart()" name="Checkout"/> 
</form>

无法找到我想要的答案,请说清楚。

4 个答案:

答案 0 :(得分:0)

从表单中删除action,从提交按钮中删除ng-click。因此,重定向到submitCart()方法

中的结帐页面

答案 1 :(得分:0)

试试这个,

HTML

 <form novalidate action="#"
    ng-submit="submitCart()" class="form">
        <input class="btn btn-primary btn-flat" type="submit" ng-click="submitCart()" name="Checkout"/> 
    </form>

JS

 $scope.submitCart= function() {
    var data = {}

            $http.post('http://localhost:8000/checkout', JSON.stringify(data)).success(function(){/*success callback*/});
        };

答案 2 :(得分:0)

首先,我想说这个问题的标题是误导性的。对于相同的操作,您不需要ng-submitng-click

使用此服务将angularjs中的数据发送到您要将其发送到的任何位置。 https://docs.angularjs.org/api/ng/service/ $ HTTP

您的表格

<form method="POST" class="form">
    <input class="btn btn-primary btn-flat" type="submit" ng-click="submitCart()" name="Checkout"/> 
</form>

控制器

$scope.submitCart = var function()
{
//Call the function to clear the items here.
//And now http call to backend.
$http({
  method: 'POST',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available

  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
}

相反,我建议您在使用服务器回调后清除输入字段。

答案 3 :(得分:0)

You need to remove the action="http://localhost:8000/checkout " from the above html for the code to work and you can use a $http service in controller to post data to that url 

the correct html is :-

 <form novalidate  
ng-submit="submitCart()" class="form">
    <input class="btn btn-primary btn-flat" type="submit" ng-click="submitCart()" name="Checkout"/> 
</form>

and in controller i.e app.js:-
app.controller("abc",function($scope,$http){
$scope.user={};
$http.post("http://localhost:8000/checkout",{data})
.success(function(data){ // response data back from server 

})
})

and bind the input values in form with ng-model on any object and initialise that object in controller  like <input type="text" ng-model='user.name' />

and when sending data replace data in $http.post with $scope.user and you can get the data in req.body on server side