agon024 agon024 - 3 months ago 8
Javascript Question

Angular post request not working not working

Here is my module:

angular.module('ngDetails', ['])
.constant('API', 'http://myserver.com/dir/api')
.controller('carDetails', carDetails)


Here is my controller:

function carDetails($scope, CarDetailService) {
CarDetailService.getCar().success(function(details) {

$scope.details = details;

carID = $scope.details['ID'];

$scope.approve = function($scope, $http, API, Message) {
$http.post( API + '/car/' + carID , { Message: Message } ).
success(function(data) {
$scope.approve = data;
})
}

});


Here is my HTML:

<div ng-controller="carDetails">
<textarea placeholder="Message" ng-model="Message"></textarea>
<button ng-click="approve()">Approve</button>
</div>


What I am trying to do is send a post request to my API that sends with it a message that a user puts in inside of a textarea box before they hit the "approve" button. But when I hit the "approve" button I get an error saying - " Cannot read property 'post' of undefined at m.$scope.approve ". How can I fix this issue?

Thanks in advance.

Answer

Thats because you need to require the DI items on your constructor , and not in the approve function.

  function carDetails($scope, CarDetailService, $http, API, Message) {
  CarDetailService.getCar().success(function(details) {

    $scope.details = details;

    carID = $scope.details['ID'];

    $scope.approve = function() {
      $http.post( API + '/car/' + carID , { Message: Message } ).
      success(function(data) {
        $scope.approve = data;
      })
    }

  });