从angularjs中的$scope在$http.post中发送动态数据

Send dynamic data in $http.post from $scope in angularjs

本文关键字:post 动态 数据 http angularjs 中的 scope      更新时间:2023-09-26

我的模板可以在这里找到http://goo.gl/xEttgl.我通过将postData声明为的全局变量来对其进行硬编码

var postData = {'result': '27'};
app.factory('mypostService', function($http) {
return {
 postFooOldSchool: function() {
   $http.post('/angularresult', JSON.stringify(postData)
   ).success(function(data, status, headers){
   }).error(function(data, status, headers){
   });
  }
 }
});
app.controller('StartUpController', function($scope, $http, myService, mypostService) {
     $scope.upvotes = 0;
     $scope.serverupvotes = 0;
     $scope.increase = function(){
             $scope.upvotes = $scope.upvotes + 1;
     };
     mypostService.postFooOldSchool(function(data) {
     });
     myService.getFooOldSchool(function(data) {
            $scope.result = data;
     });
  });

但我想做的是从StartUpController内的$scope动态发送postData,也就是说,我点击upvote按钮,我想在POST中发送$scope.upvotes的当前值,并将其显示在结果中。

我使用工厂使问题过于复杂,我找到了一个简单的解决方案,而不是使用工厂进行POST,我可以直接从控制器发送$http.POST请求。样品溶液如下

$scope.increase = function(){
    $scope.upvotes = $scope.upvotes + 1;
            var x = $scope.upvotes;
            alert(x)
            var postObject = {'result': x};
            $http.post('/angularresult', JSON.stringify(postObject)).success(function(data){
            });
            myService.getFooOldSchool(function(data) {
               $scope.result1 = data;
     });
     };