AngularJS $http.post(..) - 错误: $http 未定义。

12

我第一次尝试使用AngularJS。在使用$http.post("url", data)函数时,我会收到Error: $http is not defined的控制台消息。

在HTML页面的顶部,我已经包含了除所有其他JS导入之外的AngularJS。

由于小部件依赖等原因,我还包括了其他JavaScript库。我的脚本导入部分如下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>

我有一个控制器,用来向服务器发送一些数据:

function FormCtrl($scope) {
  $scope.sendData = function(){
        var data = "firstName=" + $scope.firstName + "&" +
            "lastName=" + $scope.lastName + "&" +
            "address=" + $scope.address + "&" +
            "postcode=" + $scope.postcode;

        $http.post("/data/person/put", data);
     };
}

sendData函数绑定在一个按钮上。一切正常,直到调用$http.post(...)时控制台输出错误信息。

完整的错误列表如下:

Error: $http is not defined
$scope.sendData@http://localhost:8080/angularjs/:96
Mc/x/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:71
ec[c]</</</<@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:142
e.prototype.$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:87
e.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:87
ec[c]</</<@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:142
c.event.handle@http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:63
c.event.add/o@http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:57

https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js
Line 61

我需要做些什么来配置AngularJS以使用$http.post函数吗?

我直接从AngularJS文档的Shortcut Methods部分中提取了用法,文档在这里:http://docs.angularjs.org/api/ng.$http

有人可以帮忙吗?

谢谢 Adam

1个回答

23

function FormCtrl($scope) { 应该改为 function FormCtrl($scope, $http) {

您需要将所有所需的服务注入到控制器中,在这种情况下,您正在使用 $scope$http 服务,但是您只注入了 $scope,这是错误的原因。

例如:

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

您可以在这里阅读有关使用缩小版时注入的复杂性的说明here,阅读关于缩小版的说明


已经尝试过并且完全可用了。谢谢您的快速回复。回复太快了,我甚至还没来得及接受您的答案。但我会的。再次感谢! - Adam Davies
1
您可以在http://docs.angularjs.org/tutorial/step_05阅读有关缩小注入时可能出现的问题的说明。 - Arun P Johny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接