2012-12-07 34 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'];