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));
});
Related
I am getting the infamous unknown provider error, and looked into every potential answer up here but I think that I am missing something:
app.js
var myApp = angular.module('myApp', [
'ngResource',
'myAppControllers',
'myAppServices',
'myAppFilters'
]).config([
'$locationProvider',
function(
$locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: false
});
}]);
var myAppControllers = angular.module('myAppControllers', []);
var myAppServices = angular.module('myAppServices', []);
var myAppFilters = angular.module('myAppFilters', []);
Item.js
myAppServices.factory('Item',
function($resource) {
return $resource('/api/items/:id');
});
ItemService.js (1)
myAppServices.factory('itemService',
function($q,
$http,
Item) {
return {
delete: function(id){
// Item, $q and $http are undefined here
return Item.delete({id: id}).$promise;
}
};
});
alternative ItemService.js (2)
myAppServices.factory('itemService', [
'$q',
'$http',
'Item', // If I don't inject it here I can use this service with $q and $http
function($q,
$http,
Item) {
return {
delete: function(id){
return Item.delete(id).$promise;
}
};
}]);
And in my controller:
myAppControllers.controller('ItemsCtrl', [
'$scope',
'itemService',
function(
$scope,
itemService) {
var ctrl = this;
ctrl.ItemService = ItemService;
ctrl.deleteItem = function(id){
ctrl.itemService.delete(id)
.then(function(response){
console.log(response);
}, function (error) {
console.log(error);
});
};
}]);
So if I try like in (1), I am getting undefined.delete is not a function in itemService.
If I try as in (2), the app fails to load with:
Unknown provider: ItemProvider <- Item <- itemService
So what am I doing wrong?
You have multiple issues here.
You need to have myAppServices as a dependency of myAppControllers in order to use it in a controller.
So, following should be how you do it:
var myAppServices = angular.module('myAppServices', []);
var myAppControllers = angular.module('myAppControllers', ['myAppServices']);
In myAppServices module you have Item service which uses $resource but you haven't injected ngResource as a dependency of myAppServices.
Here's your code in plunker without errors
EDIT: Also make sure all your files are included in index.html properly!
i think in $resource ur are missing argument it should look like
$resource('/api/items/:id', {id:'#id'});
Try (1) again , undefined is because of this
and also ur delete should be look like this
return Item.delete({id : id}).$promise;
I am trying to create and use a new service in AngularJS, however,
I get the following error -
Error message
ProjectService.one is not a function
The Javascript -
var app = angular.module('app', ['ngRoute']);
app.service('ProjectService', function () {
this.one = function one() {
console.log('test service');
};
});
app.controller('ProjectsController', ['$scope', function (ProjectService, Test) {
ProjectService.one();
}]);
There is something wrong in your controller declaration. Your ProjectService parameter matches the $scope service. Do this instead;
app.controller('ProjectsController', ['$scope', 'ProjectService', 'Test', function ($scope, ProjectService, Test) {
ProjectService.one();
}]);
The service-parameters must match the array of services (same number and order)
You've to inject the ProjectService and other required dependent modules as mentioned below:
app.controller('ProjectsController', ['$scope','ProjectService','Test', function ($scope,ProjectService, Test) {
ProjectService.one();
}]);
I have a method in my controller $scope.get another method $rootScope.search. I am writing the unit tests using Karma and Jasmin.
When I am trying to test the method $rootScope.search it throwing an error, what I am doing wrong?
Code is as follows:
Ctrl.js
App.controller('Ctrl', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.get = function(search){ // return some data from service };
$rootScope.search = function(data){
$scope.get(data);
};
}]);
Ctrl.spec.js
describe('Ctrl', function(){
beforeEach(module('app'));
var $controller, $scope = {}, $rootScope = {};
beforeEach(inject(function(_$controller_, _$rootScope_){
$controller = _$controller_;
$rootScope = _$rootScope_;
}));
describe('Data', function(){
beforeEach(function() {
$controller('Ctrl', { $scope:$scope, $rootScope:$rootScope});
spyOn($scope, 'get');
});
it('$rootScope.search', function(){
$rootScope.search();
expect($scope.get).toHaveBeenCalled();
});
})
});
Error
TypeError: $scope.get is not a function at Scope.$rootScope.search
Please help.
Actually I have to use the same from view as a global method.
If you want to provide global methods on $rootScope, do it from a .run block instead of a controller.
App.run([$rootScope', function($rootScope){
function get = function(search){ // return some data from service };
$rootScope.search = get;
}]);
But putting common functions in a factory is the recommended approach.
App.factory('mySearch', function(){
function get = function(search){ // return some data from service };
return { search: get };
});
Then inject the custom search in your controllers:
App.controller('Ctrl', ['$scope', 'mySearch', function($scope, mySearch){
var vm = $scope;
vm.data = mySearch.search(data);
}]);
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
}]
);
I have declared my app and have one controller (for demonstration purposes):
var module = angular.module("app", [])
module.controller("modalCtrl", ["$scope", function ($scope, dataService) {
$scope.printEntity = function () {
console.log(dataService.getEntityArray());
}
}]);
And a service:
module.factory("dataService", function () {
var entityArrayService = [1,2];
return {
getEntityArray: function () {
return entityArrayService;
}
};
});
When I call $scope.printEntity from my view, I'm always told dataService.getEntityArray() is undefined.
I've loaded the service as a dependency and declared my entityArrayService array outside of my return statement. I've looked high and low for an answer but to no avail. My goal is to share a piece of data between two controllers, but at the minute I can't even use one controller to retrieve data.
The service isn't loaded as a dependency. Change this line:
module.controller("modalCtrl", ["$scope", function ($scope, dataService) {
to this:
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
You are using strict syntax for dependencies declaration. So if you add a parameter to your controller, you must add its declaration too.
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
...
}
You didn't inject dataService in your controller. Try with:
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
// ...
});
The injection of the service in the controller is missing:
please correct to:
...
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
...
The other code is correct.