lundi 29 février 2016

Angular JS: Passing input parameters in HTTP service (POST)

I'm new to Angular JS and have been stuck in this problem.

<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>

What I've been trying to do is to send a parameter as an input value of HTTP request when the testClick is invoked to run the POST method, based on which fruit (i.e. the contents of the for-loop) has been chosen. (In this example, I'm trying to run a Route method of Laravel 5.2).

So far, I have found some postings on Stackoverflow, which are apparently relevant to this task. The code above is modified several times, following the advice of those postings.

I do understand this causes an error, but I'm clueless as to what is actually wrong and what I need to do instead.

ANY advice will be appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire