2012-12-07 37 views
191

我有以下的角功能:

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

但每当这个函数被调用,我在我的控制台得到ReferenceError: $http is not defined。有人能帮助我理解我在这里做错了什么吗?

回答

360

可能您没有将$http服务注入您的控制器。有几种方法可以做到这一点。请参阅this reference about DI。然后,它会非常简单:

function MyController($scope, $http) { 
    // ... your code 
} 
+16

谢谢!我想知道为什么Angular自己的文档(http://docs.angularjs.org/tutorial/step_05)有这个错误。 – Anurag

79

我已经经历了同样的问题了,我用

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

它运作良好。

0

要完成Amit Garg answer,有几种方法可以在AngularJS中注入依赖关系。


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

var MyController = function($scope, $http) { 
    // ... 
} 
MyController.$inject = ['$scope', '$http'];