Reputation: 4173
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!
Upvotes: 0
Views: 135
Reputation: 489
@YMD - not sure if this is so relevant now, your question has probably been answered by now but since you have not marked any as the right answer, I am responding with this. Please mark it as correct answer if it answers your question.
The testParameter is undefined in the controller. either use $scope from within the controller - $scope.testParameter=" "; or bind it to some object and use object.testParameter.
Unless the View passes the variable to the controller, the controller has no way of knowing about it so, testParameter remains just a View scoped variable, with no value assigned to it, and hence, undefined.
Upvotes: 0
Reputation: 8325
In $http
url key there is improper concatenation done, see following fixed code:
$http({
method : "POST",
url : "/fruits/add/"+ id
}).then(function addSucces(response) {
$scope.testBind =response.data;
}, function addError(response) {
$scope.testBind = "Error!";
});
Upvotes: 0
Reputation: 7225
This:
url : "/fruits/add/".id
should be this:
url : "/fruits/add/" + id
You're saying 'gimme the id property of a string' - that aint gonna work!
Upvotes: 0