AngularJs ReferenceError: $http is not defined

AngularjsJavascript FrameworkAngular Http

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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
}

Solution 2 - Angularjs

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.

Solution 3 - Angularjs

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'];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChubby BoyView Question on Stackoverflow
Solution 1 - AngularjsƁukaszBachmanView Answer on Stackoverflow
Solution 2 - AngularjsAmit GargView Answer on Stackoverflow
Solution 3 - AngularjsMistalisView Answer on Stackoverflow