1

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.

2 Answers 2

1

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;
      })
    }

  });
Sign up to request clarification or add additional context in comments.

Comments

0

When you are working with the angular services or your own build services and you want to use them in controller on services you need to inject them

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

Inject like this

function carDetails($scope, CarDetailService,$http) {
  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;
      })
    }

  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.