I have a simple angularjs application and I would like to make http request, but I really don't know why it is not working. Here is my controller:
(function () {
'use strict';
/**
* #ngdoc function
* #name app.controller:HomeCtrl
* #description
* # HomeCtrl
* Controller of the app
*/
angular.module('BlurAdmin.pages.dashboard')
.controller('HomeCtrl', ['$scope', '$rootScope', '$stateParams', '$http', '$location', HomeCtrl ]);
function HomeCtrl($scope, $http, $location) {
$scope.samples = [['a', 'b', 'c'], ['d', 'e', 'f']];
console.log($http);
console.log($scope);
console.log($location);
console.log(window.location.hostname);
$http.get(
'http://localhost' + ':7000/samples',
{}
).then(function(err, data){
if (err){
console.log(err);
}
console.log(data);
},
function(err, data){
});
var varApplist = this;
}
})();
I my patial homeCtrl:
<div id="page-wrapper" ng-controller="HomeCtrl">
......
<div>
in my index.html
when I try to run, I am having this error:
TypeError: $http.get is not a function
at new HomeCtrl (http://localhost:4001/app/pages/dashboard/home/homeCtrl.js:21:11)
at invoke (http://localhost:4001/bower_components/angular/angular.js:4570:17)
at Object.instantiate (http://localhost:4001/bower_components/angular/angular.js:4578:27)
at http://localhost:4001/bower_components/angular/angular.js:9460:28
at http://localhost:4001/bower_components/angular-ui-router/release/angular-ui-router.js:4081:28
at invokeLinkFn (http://localhost:4001/bower_components/angular/angular.js:9099:9)
at nodeLinkFn (http://localhost:4001/bower_components/angular/angular.js:8586:11)
at compositeLinkFn (http://localhost:4001/bower_components/angular/angular.js:7975:13)
at publicLinkFn (http://localhost:4001/bower_components/angular/angular.js:7855:30)
at updateView (http://localhost:4001/bower_components/angular-ui-router/release/angular-ui-router.js:4021:23) <div ui-view="" class="ng-scope">
when I log $location and $http, I have and empty object.
.controller('HomeCtrl', ['$scope', '$rootScope', '$stateParams', '$http', '$location', HomeCtrl ]);
function HomeCtrl($scope, $http, $location) {
Except for $scope, the actual parameters of your function don't match, at all, with the dependencies declared at the beginning of the array.
Do yourself a favor, and stop using this ugly and bug-prone array notation. Use ng-annotate to make your code minifiable automatically.
Also note that the callback passed to then() will be called with a single argument. So the data argument you have there is useless.
need to match your dependency injection sequence with the string values
.controller('HomeCtrl', ['$scope', '$rootScope', '$stateParams', '$http', '$location',
function HomeCtrl($scope, $rootScope,$stateParams, $http, $location) {
When you are initializing the angular module, need to add empty squire brackets for the module injection
angular.module('BlurAdmin.pages.dashboard',[])
also remove err in your promise (then)
.then(function(data) {
console.log(data); // success response
},
function(data) {
console.log(data); // error resoponse
});
full controller
(function () {
'use strict';
angular.module('BlurAdmin.pages.dashboard',[])
.controller('HomeCtrl', ['$scope', '$rootScope', '$stateParams', '$http', '$location',
function HomeCtrl($scope, $rootScope,$stateParams, $http, $location) {
$scope.samples = [['a', 'b', 'c'], ['d', 'e', 'f']];
console.log($http);
console.log($scope);
console.log($location);
console.log(window.location.hostname);
$http.get(
'http://localhost' + ':7000/samples',
{}
).then(function(data){
console.log(data);
},
function(err){
console.log(err);
});
var varApplist = this;
}])
})();
Related
I have a controller called UserCtrl and it depends on a service called UserService. When the view that uses the controller UserCtrl loads I get an error:
Unknown provider: UserServiceProvider
Here is my service code:
angular.module('UserService', []).service('UserService', ['$rootScope', '$route', '$http', '$filter', function ($rootScope, $route, $http, $filter) {
function loadType() {
var deferred = $q.defer();
$http.get('json/type.json').success(function (response) {
var typeoflaw = response;
}).error(function (status, data) {
console.log("error trapped");
});
deferred.resolve(typeoflaw);
return deferred.promise;
};
}]);
Here is my controller code:
JBenchApp.controller('UserCtrl', ['$scope', '$routeParams', '$http', '$filter', 'UserService',
function ($scope, $routeParams, $http, $filter, UserService) {
// Get the preferences information
UserService.loadType()
.then(function (lawtypes) {
$scope.typeoflaw = lawtypes;
});
$scope.SavePreferences = function () {
};
}]);
What did I do wrong?
EDITED TO SHOW JBenchApp code:
var JBenchApp = angular.module('JBenchApp', [
'ngRoute',
'UserService'
]);
This brings to mind a question that has bugged me. What order do you declare your JS files for angular in the index.html page? Mine are currently:
<script src="../js/angular.min.js"></script>
<script src="../js/angular-route.min.js"></script>
<script src="../js/app.js"></script>
<script src="../js/services.js"></script>
<script src="../js/controllers.js"></script>
<script src="../js/directives.js"></script>
May be try this
angular.module('UserService').controller('UserCtrl', ['$scope', '$routeParams', '$http', '$filter', 'UserService',
function ($scope, $routeParams, $http, $filter, UserService) {
//controller code here
}]);
I'm changing my angular controllers to minification friendly but I am getting a error with my $resource calls. all of my factories look the same as the one i am posting. I have followed the tutorials online but it is not working out for me.
//'use strict';
app.controller('documentCtrl', ['$scope', '$upload', '$filter', '$route', '$sessionStorage','$sce', '$q', '$modal', '$http', '$location', '$rootScope', function (
$scope, $upload, $filter, $route, $sessionStorage, $sce, $q, $modal, $http, $location, $rootScope) {
$scope.docTypes = Type.query(function () { });
$scope.selectType = function () {
var id = $scope.typeId.TypeId
$http.get('/api/apiType/' + id)
.success(function (result) {
$scope.TypeName = result.TypeName
console.log($scope.TypeName);
});
};//
$scope.docPipes = Pipe.query(function () { });
$scope.selectPipe = function () {
var id = $scope.pipeId.PipeId
$http.get('/api/apiPipe/' + id)
.success(function (result) {
$scope.PipeName = result.PipeName
console.log($scope.PipeName);
});
};//
Factory
'use strict'
app.factory('Type',['$resource', function ($resource) {
return $resource('/api/apiType/:id', { id: '#_id' }, {
get: {
method: 'GET', isArray: false // this method issues a PUT request
}
}, {
stripTrailingSlashes: false
});
}]);
app.factory('TypeUpdate',['$http', function ($http) {
return {
update: function (doc) {
return $http.put('/api/apiType/' + doc.TypeId, doc);
}
};
}]);
Error
ReferenceError: Type is not defined
Update
Type is a $resource call defined in my factory.
Is this the way the controllers should be defined? The examples I found online did not include variables.
app.controller('documentCtrl', ['$scope', '$upload', '$filter', '$route', '$sessionStorage','$sce', '$q', '$modal', '$http', '$location', '$rootScope', 'ngTableParams', 'notificationFactory', 'Type', 'Document', 'Plant', 'Pipe', 'Company', 'Location', function (
$scope, $upload, $filter, $route, $sessionStorage, $sce, $q, $modal, $http, $location, $rootScope, ngTableParams, notificationFactory, Type, Document, Plant, Pipe, Company, Location) {
You have declared a factory called "Type". This needs to be listed in your controller dependencies.
I have an unknown provider error and I'm not sure how to solve it. I think my services, controllers are declared properly. I have tried everything but it doesn't work. my photosFactory factory doesn't work. it's not injected into controller. I'd appreciate any help.
My app.js :
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
my controllers.js :
angular.module('starter.controllers', [])
.controller('PlaylistsCtrl', ['$scope', 'photosFactory', '$http', function ($scope, $http, Util, $ionicLoading, $location, photosFactory) {
$ionicSideMenuDelegate.canDragContent(true);
$scope.allDeals = [];
$scope.navigate = function(url){
$location.path(url);
};
photosFactory.getPhotos().success(function(data){
$scope.allDeals= data;
});
}])
My services.js :
angular.module('starter.services', [])
.factory('photosFactory', function($http) {
return{
getPhotos : function() {
return $http({
url: 'http://www.somecompany.co.uk/bigcapi/feeds/deals/company_id/88',
method: 'GET',
params: {all: '1', mobileready: 1}
})
}
}
})
I think it's because you don't inject $http in your factory.
Try it
.factory('photosFactory', [ '$http', function($http) {
return{
getPhotos : function() {
return $http({
url: 'http://www.somecompany.co.uk/bigcapi/feeds/deals/company_id/88',
method: 'GET',
params: {all: '1', mobileready: 1}
})
}
};
}]);
There is also a problem when declaring your controller
['$scope', 'photosFactory', '$http', function ($scope, $http, Util, $ionicLoading, $location, photosFactory) {
The order is very important so you must have something like this
['$scope', 'photosFactory', '$http', 'Util', '$ionicLoading', '$location', function ($scope, photosFactory, $http, Util, $ionicLoading, $location,) {
Well,
You only declared 3 injectables,
controller('PlaylistsCtrl', ['$scope', 'photosFactory', '$http',
but want to use 6 - that is not good.
function ($scope, $http, Util, $ionicLoading, $location, photosFactory)
Mind the order.
You haven't included your HTML so can't confirm - did you include your services javascript in the index?
Assuming you fix your various import issues, this seems the most likely reason.
Actually you should only declare angular.module('starter.controllers', []) once. You should use angular.module('starter.controllers') instead. (eg. angular.module('starter.controllers', []).controller ...
I have the following in a controller.
$rootScope.$on('progressbarEvent', function (event, data) {
$rootScope.progresscurrent = data.currentprogress;
console.log('Event listening: ' + $rootScope.progresscurrent);
});
I have this in a factory service.
$rootScope.$emit('progressbarEvent', dataFactory.currentprogress);
$on is returned undefined. Anyone knows the cause of this?
My controller is:
app.controller('indexcontroller', ['$rootScope','$scope', '$http', 'dataFactory',
function ($scope,$http,$rootScope, dataFactory) {
The order of dependencies has to be consistent with the array it was declared in:
app.controller('indexcontroller', ['$rootScope','$scope', '$http', 'dataFactory',
function ($rootScope, $scope, $http, dataFactory) {
I wrote a directive and a service. The directive calls a timeout function in the service. However, once the $timeout is reached, it throws an error:
TypeError: object is not a function
Original $scope.msg is not displayed. And the $timeout function does not wait for (20sec) to call the callback (or so I assume, since the $scope.msg changes right away).
I am absolutely lost. I found a few questions regarding timeouts, but none of them seem to have this problem. This one is as close as I got, and I am already following that answer Angularjs directive TypeError: object is not a function.
Here is a Plunker to the code:
http://plnkr.co/edit/xrepQOWIHlccbW5atW88?p=preview
And here is the actual code.
angular.module('myApp', [
'ui.bootstrap',
'myApp.services',
'myApp.directives',
]);
angular.module('myApp.directives', []).
directive('logoutNotification', [
function(admin) {
return {
restrict: "E",
template: "<div>{{msg}}</div>",
controller: ["$scope", "$timeout", "admin",
function($scope, $timeout, admin) {
$scope.msg = "Hey, no timeout yet";
$scope.resetNotification = function() {
admin.resetNoticeTimer(function(){
$scope.msg = "Hey, I'm back from timeout"
});
};
}
],
link: function(scope) {
scope.resetNotification();
}
};
}
]);
angular.module('myApp.services', []).
factory('admin', ['$rootScope', '$location', '$timeout',
function($rootScope, $timeout, $location, admin) {
var noticeTimer;
return {
resetNoticeTimer: function(cb) {
if (noticeTimer) {
$timeout.cancel(noticeTimer);
}
noticeTimer = $timeout(cb(), 20000);
}
};
}
]);
Thanks in advance!
You have misordered the dependencies.
Your code:
factory('admin', ['$rootScope', '$location', '$timeout',
function($rootScope, $timeout, $location, admin) {
Should be:
factory('admin', ['$rootScope', '$timeout', '$location',
function($rootScope, $timeout, $location) {