AngularJs ReferenceError: $http is not defined
Asked Answered
M

3

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?

Meurer answered 7/12, 2012 at 8:0 Comment(0)
A
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
}
Armpit answered 7/12, 2012 at 8:12 Comment(1)
Thanks! I wonder why Angular's own documentation (docs.angularjs.org/tutorial/step_05) has this error.Philippines
H
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.

Huebner answered 2/3, 2014 at 8:58 Comment(0)
G
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'];
Gaynellegayner answered 20/10, 2016 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.