I'm trying out AngularJS for the first time. When using the $http.post("url", data)
function, I'm getting a Error: $http is not defined
console message.
At the top of my HTML page I am including AngularJS after all other JS imports.
I have also included other JavaScript libraries due to widget dependencies etc. My script imports section looks like this:
<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>
I have a controller which I'm using to send some data to the server:
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);
};
}
The sendData
function is attached to a button. All works fine until the call to $http.post(...)
at which point the console outputs the error.
The full error listing is:
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
Do I have to do something else to configure AngularJS to use the $http.post
function?
I lifted the usage straight from the AngularJS Shortcut Methods section of the documentation here: http://docs.angularjs.org/api/ng.$http
Can anyone help?
Thanks Adam
function FormCtrl($scope) {
should be function FormCtrl($scope, $http) {
.
You need to inject all the services required to the controller, in this case you are using $scope
and $http
service, but you have injected only $scope
that is the cause of the error.
Ex:
function FormCtrl($scope, $http) {
....
}
FormCtrl.$inject = ['$scope', '$http'];
You can read a note about complications in injection with minification here, read A Note on Minification
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With