2016-02-29 125 views
0

我是Angular JS的新手,一直困在这个问题中。Angular JS:在HTTP服务(POST)中传递输入参数

<body class="homepage" ng-app="angularApp"> 

    <div ng-controller="myCtrl"> 
     <ul> 
      @foreach ($fruits as $fruit) 
      <!-- looping --> 
      <input type="hidden" value="{{$fruit->id}}" ng-model="testParameter"> 
      <button ng-click="testClick(testParameter)" class="adding_item_to_cart">Add to Cart</button> 
      @endforeach 
     </ul> 
     <p ng-bind="testBind"></p> 
    </div> 

<script type="text/javascript"> 
    var angularApp = angular.module('angularApp', []); 
    angularApp.controller('myCtrl', function($scope, $http) { 
     $scope.testClick = function(id) { 
      $http({ 
       method : "POST", 
       url : "/fruits/add/".id 
      }).then(function addSucces(response) { 
       $scope.testBind =response.data; 
      }, function addError(response) { 
       $scope.testBind = "Error!"; 
      }); 
     } 
    }); 
</script> 

</body> 

我一直试图做的是发送一个参数作为HTTP请求的输入值时testClick被调用运行POST方法,在此基础上fruit(即换的内容循环)已被选中。 (在这个例子中,我试图运行Laravel 5.2的Route方法)。

到目前为止,我在Stackoverflow上发现了一些贴子,这些贴子显然与此任务有关。上述代码根据这些帖子的建议进行了几次修改。

明白这会导致一个错误,但我不知道什么是真正的错误和我需要做的,而不是。

任何意见将不胜感激!

回答

0

此:

url : "/fruits/add/".id 

应该是这样的:

url : "/fruits/add/" + id 

你说 '给我一个字符串的id属性' - 这是不是要去工作!

+0

谢谢你的回复。不幸的是,这会导致另一个错误。由于URL呈现为“http:// localhost:8000/fruits/addundefined”,因此POST方法未正确运行。 – Hiroki

+0

所以它看起来像你的testParameter没有被设置,然后 – mindparse

0

$http网址关键有不当拼接完成,请参阅下面的固定码:

  $http({ 
       method : "POST", 
       url : "/fruits/add/"+ id 
      }).then(function addSucces(response) { 
       $scope.testBind =response.data; 
      }, function addError(response) { 
       $scope.testBind = "Error!"; 
      }); 
+0

谢谢你的回复。不幸的是,这会导致另一个错误。由于URL呈现为“http:// localhost:8000/fruits/addundefined”,因此POST方法未正确运行。 – Hiroki

+0

显然它意味着'testParameter'没有正确传递,导致'id'未定义,并且url变成了你提到的那个。 –

0

@YMD - 不知道这是现在这么重要,你的问题可能已经通过,但现在既然你已经回答没有标记为正确的答案,我对此作出了回应。如果它回答你的问题,请标记为正确答案。

testParameter在控制器中未定义。要么从控制器内使用$ scope - $ scope.testParameter =“”;或将其绑定到某个对象并使用object.testParameter

除非视图传递变量的控制器,所述控制器具有无法知道关于它的这样的方式,保持testParameter只需查看范围的变量,没有分配给它值,因此,未定义