Angular双向数据绑定和http.post问题

时间:2014-08-19 08:50:10

标签: angularjs http post

目标:通过范围和控制器实现数据库与视图之间的双向数据绑定

我正在尝试使用angular

发布到一个安静的数据库

当我单击拇指或拇指朝下时,范围会改变o.k并反映在视图中

但是如何使用http post实时将其放到一个安静的数据库?

这是HTML

     <div ng-controller="ordersCtrl">

     <div class="span0 well votingWidget">
                <div class="votingButton" ng-click="upVoteOrder(order)">
                    <i class="icon-thumbs-up "></i>
                </div>
                <div class="badge ">
                    <div>{{order.upVoteCount}}</div>
                </div>
                <div class="votingButton" ng-click="downVoteOrder(order)">
                    <i class="icon-thumbs-down"></i>
                </div>




          Heres the Controller: My issue lies here in the http.post command 


  .controller("ordersCtrl", function ($scope, $http, ordersUrl) {

   $scope.downVoteOrder = function(order) {
       $scope.selectedOrder = order;
        order.upVoteCount--;
         $http.post(orderUrl,  order.upVoteCount)
        .success(function (data) {
            $scope.data.orderupVoteCount = data.id;

        })
};

});

注意:我可以使用以下代码

将表单数据成功发布到restful数据库
     $scope.sendOrder = function (shippingDetails) {
        var order = angular.copy(shippingDetails);
        order.products = cart.getProducts();
        $http.post(orderUrl, order)
            .success(function (data) {
                $scope.data.orderId = data.id;
                cart.getProducts().length = 0;
            })
            .error(function (error) {
                $scope.data.orderError = error;
            }).finally(function () {
                $location.path("/uploaded");
            });
    }

1 个答案:

答案 0 :(得分:0)

您应该使用单独的服务来处理http帖子。

var app = angular.module("myApp", []);

    app.factory("OrderService", ["$http", function ($http) {

    this.PostDownVote =  function(orderUrl, upVoteCount) {
            return $http.post(orderUrl, upVoteCount);   
    }    

    this.PostOrder = function(orderUrl, order) {
     // do something
    }

    return this;
}]);

现在将此OrderService注入您的控制器并使用它。

app.controller("ordersCtrl", function ($scope, $http, ordersUrl, OrderService) {

    $scope.downVoteOrder = function(order) {
        $scope.selectedOrder = order;
        order.upVoteCount--;
        OrderService.PostDownVote(ordersUrl, order.upVoteCount)
                     .success(data) {// do            something}
                      .error(data) {// do something}

    }
});