202

I have the following Angular function:

$scope.updateStatus = function(user) {    
    $http({
        url: user.update_path, 
        method: "POST",
        data: {user_id: user.id, draft: true}
    });
};

But whenever this function is called, I am getting ReferenceError: $http is not defined in my console. Can someone help me understanding what I am doing wrong here?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Chubby Boy
  • 30,942
  • 19
  • 47
  • 47

3 Answers3

377

Probably you haven't injected $http service to your controller. There are several ways of doing that.

Please read this reference about DI. Then it gets very simple:

function MyController($scope, $http) {
   // ... your code
}
ŁukaszBachman
  • 33,595
  • 11
  • 64
  • 74
  • 18
    Thanks! I wonder why Angular's own documentation (http://docs.angularjs.org/tutorial/step_05) has this error. – Anurag Oct 09 '13 at 11:49
83

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

Amit Garg
  • 3,867
  • 1
  • 27
  • 37
4

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];
Community
  • 1
  • 1
Mistalis
  • 17,793
  • 13
  • 73
  • 97