AngularJs ReferenceError:未定义$ http


199

我有以下Angular函数:

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

但是无论何时调用此函数,我都会进入ReferenceError: $http is not defined控制台。有人可以帮助我了解我在做什么错吗?

Answers:



81

我在使用时遇到了同样的问题

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

我已经将上面的代码更改为下面的代码。请记住,如下所示包含$ http(2次)。

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

而且效果很好。


4

只是为了完成Amit Garg的回答,有几种方法可以在AngularJS中注入依赖项。


您还可以使用$inject添加依赖项:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.