I defined a factory that makes a get request but when I inject it in a controller it always throws an undefined error.
This is the factory:
(function() {
'use strict';
var app = angular
.module('myApp');
app.factory('homeFactory', homeFactory);
function homeFactory ($q, $http, $location) {
var data = {};
data.getProducts = getProducts;
function getProducts() {
return $http.get('http://localhost:8000/api/v1/products')
.error(errorMessage);
}
function errorMessage(response) {
console.log('There was an error', response);
}
return data;
}
})();
This is the controller:
(function() {
'use strict';
var app = angular
.module('myApp');
app.controller('homeController', homeController);
homeController.$inject =[homeFactory];
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
})();
It appears to be ok, but the console throws:
Uncaught ReferenceError: homeFactory is not defined
The problem is in your DI annotation. You should only use strings
homeController.$inject = ['homeFactory'];
See https://docs.angularjs.org/guide/di#-inject-property-annotation
The $inject property is an array of service names to inject.
The controller function supports dependency injection. You don't need to use the $injector directly. Try this:
var app = angular
.module('myApp');
app.controller('homeController', homeController);
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
The angular runtime will find the homeFactory service, and automatically pass it to your controller function when it's called.
In controller you shall put factory in dependecies
app.controller('homeController', ['homeFactory', '$scope',
function (homeFactory, $scope){
//scope code goes here
}]
);
Related
I created custom service
(function () {
"use strict";
angular
.module("common.services")
.factory("redirectService",
["$q", "$location",
redirectService])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('redirectService');
});
function redirectService($q, $location){
...
var redirect = function() {
...
};
return {
doRedirect: redirect
};
}
inside my other controller where I'm injecting this redirectService I'm trying to call this publish doRedirect method
angular
.module("myModule")
.controller("MyController",
["$scope",
"redirectService"
MyController]);
function MyController(redirectService){
vm.doClick = function() {
redirectService.doRedirect();
}
}
Here I'm getting error on calling doRedirect method
Error: redirectService.doRedirect is not a function
You have an imbalance of number of arguments in dependency array and function arguments for MyController
Change
function MyController(redirectService){
To
function MyController($scope, redirectService){
MyController function has two arguments first $scope, second redirectService
angular
.module("myModule")
.controller("MyController",
["$scope",
"redirectService"
MyController]);
function MyController($scope, redirectService){
vm.doClick = function() {
redirectService.doRedirect();
}
}
I have a very simple service and a controller attempting to get some information from it, but I keep getting .methodName is not a function.
Here is the service, apiService.js :
(function (module) {
function api() {
var sharedService = {};
sharedService = {
getAll: function () {
return 'test';
}
};
return sharedService;
}
module.factory("api", api);
}(angular.module("anbud")));
Then I attempt to use my method getAll in the controller, like this:
(function () {
'use strict';
angular.module('anbud')
.controller('BasicExampleCtrl', ['$scope', 'api', function (api, $scope) {
// on successfull request
function onJson(json) {
$scope.data = json;
}
// error getting json
function onError() {
throw 'error getting json';
}
function initialize() {
api.getAll()
.then(onJson, onError);
}
initialize();
}]);
}());
But I get the error:
TypeError: api.getAll is not a function
at initialize (basic-example.js:67)
Any help is appreciated thank you.
You have interchanged the dependencies sequence inside controller factory function, the sequence must be same as they are included in DI array while injecting in function.
Code
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope, api) { //<- first $scope then api.
try it like this:
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope,api) {
I'm new to angularjs an i'm trying to create a login form but i'm getting following error :
Cannot read property 'ClearCredentials' of undefined.
I have used some tutorial stuff. But now i started to create an application from scratch. But i'm stuck with the AuthenticationService.js
This is what i have done
app.js
(function(angular) {
angular.module("app.directives", []);
angular.module("app.AuthenticationService", []);
angular.module("app.controllers", []);
angular.module("app", ['ngRoute','ngResource','routes','app.directives','app.controllers',"app.AuthenticationService"]);
}(angular));
controller.js
//LoginController
(function (angular) {
var LoginController = function($scope,$location,AuthenticationService){
var vm = this;
//todo vm.login = login;
(function initController() {
// reset login status
// calling function from AuthenticationService
AuthenticationService.ClearCredentials();
})();
/* TODO: This has not been tested yet
function login(){
vm.dataLoading = true;
// constructor from AuthenticationService
AuthenticationService.Login(vm.username,vm.password, function(response){
//Check if method respons === success
if (response.success) {
// calling function from AuthenticationService
AuthenticationService.SetCredentials(vm.username, vm.password);
$location.path('/');
} else {
// use function from FlashService
// FlashService.Error(response.message);
// vm.dataLoading =false;
}
});
}*/
}
LoginController.$inject = ['$scope','$location'];
angular.module("app.controllers").controller("LoginController", LoginController);
}(angular));
AuthenticationService.js
(function (angular) {
var AuthenticationService = function($http, $cookieStore, $rootScope, $timeout, UserService) {
var service = {};
service.ClearCredentials = ClearCredentials;
function ClearCredentials() {
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic ';
}
return service;
}
AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService'];
angular.module("app.AuthenticationService").factory("AuthenticationService", AuthenticationService);
})(angular);
If you have suggestions for this code please let me also know.
You inject two parameters:
LoginController.$inject = ['$scope','$location'];
But then you refer to the third one. Isn't this a problem?
Check if the inline version would work:
angular.module("app.controllers").controller("LoginController", funtion($scope,$location,AuthenticationService){
...
}
If it does, then there is an issue with Angular injection.
i have used Angularjs and i wanna call getcustomer function from one controller to another controller i have so many doing gooogling but i don't have an idea that how to call that
i have write below code which i used
var app = angular.module('Napp', []);
app.controller('GetAlphabetical', function ($scope, $http) {
function getCutomers() {
$scope.loading = true;
$http.get('#Url.Content("~/Home/GetPesrons")').then(function (response) {
//var _data = angular.fromJson(response);
$scope.loading = false;
$scope.Customer = response.data; // please check the request response if list id in data object
}, function (error) {
throw error;
})
}
});
and second controller :
app.controller('MainCtrl', function ($scope, $http) {
getCutomers()
});
Mate, you will have to follow the following steps to resolve your problem. Firstly you have you create a factory
angular
.module('Napp')
.factory('CustomerFactory', ['$http', function ($http) {
var _factory = {};
_factory.getCustomers = function () {
return $http.get('#Url.Content("~/Home/GetPesrons")');
};
return _factory;
}]);
Then you can share data and functions between multiple controllers or services
GetAlphabetical Controller :
angular
.module('Napp')
.controller('GetAlphabetical', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
MainCtrl Controller :
angular
.module('Napp')
.controller('MainCtrl', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
This can be easily done by defining it as a service and injecting it as a dependency.
var app = angular.module('myApp', []);
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
app.controller('MainCtrl', function ($scope, $http, helloWorldFromService) {
app.controller('GetAlphabetical', function ($scope, $http, helloWorldFromService) {
Angular Service
What you want to do is to somehow communicate between two controllers. This can be easily be achieved using $broadcast & $on.
Incase there is a parent child relation between your controllers, use the following.
function firstCtrl($scope){
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope){
$scope.$on('someEvent', function(event, mass) {console.log(mass)});
}
If there is no parent child relationship between your controller, then inject $rootScope and broadcast using that.
related question - https://stackoverflow.com/a/14502755/1182982
I am new to angulerJS. i have defined a factory to get data from API but when i try to put the factory in a controller i got error.
That is the factory code.
(Function () {
var CategoriesFactory = function($http) {
var factory = {};
factory.getCategorys = function(account_id){
return $http.get('http://localhost:18678/api/Transaction?account_id=2');
};
factory.getTransaction = function(acc_id){
return $http.get('http://localhost:18678/api/Transaction?acc_id=2');
};
factory.getTransactionInCategory = function(category_id, from_date, to_date){
return.$http.get('http://localhost:18678/api/transaction?category='+category_id+'&account=2&from=2015-01- 01&to=2015-12-30');
};
return factory;
};
angular.module('AccApp').factory('CategoriesFactory', CategoriesFactory);
}());
here is the controller.
app.controller('CategoriesController',
function ($scope, $routeParams, $http, CategoriesFactory) {
})
and here is the error.
Unknown provider: CategoriesFactoryProvider <- CategoriesFactory
I guess you must have forgot to inject AccApp into your mai module where you have defined your app.
angular.module("app", ['AccApp']);
Please do something like this.
Hope this helps!
Why are you trying to write angular code in a wierd way ?
The goal of angular is the simplicity
var app = angular.module('AccApp',[]);
app.factory('CategoriesFactory',function($http){// you can cut and paste this factory into a seperate file if you wish
return{
getCategorys:function(account_id){
return $http.get('http://localhost:18678/api/Transaction?account_id=2');
},
getTransaction:function(acc_id){
return $http.get('http://localhost:18678/api/Transaction?acc_id=2');
},
getTransactionInCategory : function(category_id, from_date, to_date){
return.$http.get('http://localhost:18678/api/transaction?category='+category_id+'&account=2&from=2015-01- 01&to=2015-12-30');
};
}
});
Now you can Inject this factory into your controller simply:
app.controller('CategoriesController',function ($scope, $routeParams, $http, CategoriesFactory){
console.log(CategoriesFactory.getCategorys(getCategorys));
});