how to inject factory to controller - angularjs

I am calling a function in a factory and trying to inject in the controller. But I am getting an error saying, unknown provider. Please let me know where I am going wrong.
app.factory('pdfdwn', function($scope) {
return{
download:function(){
html2canvas(document.getElementById('export'), {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 500,
}]
};
pdfMake.createPdf(docDefinition).download("Table.pdf");
}
});
return download();
}
}
});
controller:
app.controller('myctrl', function($scope,pdfdwn){
$scope.pdf = function() {
var pdd = pdfdwn.download();
};
});

1.remove $scope from factory method because you cannot inject inside.
2.Remove the return download(); from the factory, because u are already returning the download.
Inside the controller:
app.controller('myctrl', function($scope,pdfdwn){
$scope.pdf = function() {
pdfdwn.download();
};
});

Related

AngularJS Factory.XXX is not a function

I am having fits trying to get my factory/service function to work from my controller. I have seen many threads on this, and have tried various solutions, to no avail, so it leads me to believe I'm missing something simple. Here's the code (error message provided below):
'use strict';
var smacApp = angular.module('smacApp', ['ngRoute']);
smacApp.config(function($routeProvider) {
$routeProvider
.when("/login", {
templateUrl: "templates/login.html",
controller: "LoginController"
})
});
smacApp.factory('AuthenticationService', function() {
var users = ["Bob", "Joe"];
return {
all: function() {
return users;
},
first: function() {
return users[0];
}
};
});
smacApp.controller('LoginController', function($scope, AuthenticationService) {
$scope.users = AuthenticationService.all();
console.log($scope.users);
});
smacApp.run.$inject = ['$rootScope', '$routeParams'];
smacApp.run(function($rootScope, $routeParams) {
});
The error message I am receiving is:
angular.js:9778TypeError: AuthenticationService.all is not a function
at new <anonymous> (http://localhost/smac3/app.js:61:39)
at d (http://localhost/smac3/lib/angular/js/angular.min.js:34:265)
at Object.instantiate (http://localhost/smac3/lib/angular/js/angular.min.js:34:394)
at http://localhost/smac3/lib/angular/js/angular.min.js:66:112
at link (http://localhost/smac3/lib/angular/js/angular- route.js:913:26)
at J (http://localhost/smac3/lib/angular/js/angular.min.js:53:345)
at f (http://localhost/smac3/lib/angular/js/angular.min.js:46:399)
at http://localhost/smac3/lib/angular/js/angular.min.js:46:67
at http://localhost/smac3/lib/angular/js/angular.min.js:47:303
at u (http://localhost/smac3/lib/angular/js/angular.min.js:51:28) <div ng-view="" id="container" class="ng-scope">
Any help is greatly appreciated!
Maybe the syntax for your factory is correct, but I've always written them more like this:
smacApp.factory('AuthenticationService', function() {
var factory = this
factory.users = ["Bob", "Joe"];
factory.all = function() {
return factory.users;
};
factory.first = function() {
return factory.users[0]
}
return factory;
}
or
smacApp.factory('AuthenticationService', function() {
var factory = this
factory = {
users: ["Bob", "Joe"],
all: function() { return factory.users },
first: function() { return factory.users[0] }
}
return factory;
}

angularjs service error [$interpolate:interr] Can't interpolate: Factory

I am writing a Factory/Service for the first time and trying to get an image from a factory into controller but getting undefined when in the factory function for some reason.
Here is the fiddle
https://jsfiddle.net/vijay_vadlamani/2qL2Lh5r/1/
Html:-
JS:-
angular.module('myApp').factory('imageFactory', function() {
return function contentImage($scope) {
$scope.getImage = function(content) {
return getContentImage(content);
};
};
});
angular.module(myApp).controller('getImageCtrl', ['$scope', 'imageFactory', function($scope, imageFactory) {
$scope.getListImage = function(content) {
return imageFactory.getImage(content);
};
}]);
Try to declare service like this:
var app = angular.module('myApp',[]);
app.factory('imageFactory', function()
{
var service =
{
getImage: function(content)
{
return getContentImage(content);
}
};
return service
});
and use it like this:
app.controller('getImageCtrl', ['$scope','imageFactory',function($scope, imageFactory)
{
$scope.getListImage = function(content)
{
return imageFactory.getImage(content);
};
}]);
Here's demo

Can not pass data from factory to controller

I have code like this with a factory:
angular.module("mainApp", ["kendo.directives"])
.factory("getFormats", function() {
var searchStr="list&John&1&1".substr(1);
//Here I see the searchStr
return {
isType: function(){
searchStr.split('&')[0];
//Here I see the searchStr
},
username: function(){
searchStr.split('&')[1];
},
dateFormatIndex: function(){
searchStr.split('&')[2];
},
languageIndex: function(){
searchStr.split('&')[3];
}
}
})
.controller("ValidationListCtrl", function( $scope,getFormats) {
var isType=getFormats.isType(); //Here I see the undefined
var username=getFormats.username();//Here I see the undefined
var dateFormatIndex=getFormats.dateFormatIndex();//Here I see the undefined
var languageIndex=getFormats.languageIndex();//Here I see the undefined
}
But i get all the variables as undefined in controller. I also have checked the factory when i get it in controller and see it with empty object
Object {}dateFormatIndex: (){arguments: nullcaller: nulllength: 0name: ""prototype: dateFormatIndex__proto__: Empty() {}<function scope>isType: (){languageIndex: (){username: (){__proto__: Object
What am i missing?
Forgot to use return in factory methods, now it should work:)
angular.module("mainApp", ["kendo.directives"])
.factory("getFormats", function() {
var searchStr="list&John&1&1".substr(1);
return {
isType: function(){
return searchStr.split('&')[0];
},
username: function(){
return searchStr.split('&')[1];
},
dateFormatIndex: function(){
return searchStr.split('&')[2];
},
languageIndex: function(){
return searchStr.split('&')[3];
}
}
})
You are not returning the values in any of the methods inside the factory. Do something like the following :
angular.module("mainApp", ["kendo.directives"])
.factory("getFormats", function() {
var searchStr="list&John&1&1".substr(1);
//Here I see the searchStr
return {
isType: function(){
return searchStr.split('&')[0];
//Here I see the searchStr
},
username: function(){
return searchStr.split('&')[1];
},
dateFormatIndex: function(){
return searchStr.split('&')[2];
},
languageIndex: function(){
return searchStr.split('&')[3];
}
}
});
This should do the trick.
Another approach is you can use modular / revealing module pattern , which helps in encapsulation as well as code readability as below
angular.module("mainApp", ["kendo.directives"])
.factory("getFormats", function() {
var _searchStr="list&John&1&1".substr(1),
_isType = function(){
return _searchStr.split('&')[0];
},
_username = function(){
return _searchStr.split('&')[1];
}
.....
return {
isType :_isType ,
username:_username
.....
}
})
so in your controller or in another service you can get it as
getFormats.username(//arguments if required)
username.isType(//arguments if required)

angularJS service not getting called

I'm very new to AngilarJS. I am trying to write a service in angularJS.
<script>
var module = angular.module("myapp", []);
module.service('BrandService', function ($http) {
var brands = [];
this.getBrands = function()
{
return $http.get('http://admin.localhost/cgi-bin/brand.pl')
.then(function(response)
{
brands = response.brands;
alert (brands);
});
}
//simply returns the brands list
this.list = function ()
{
return brands;
}
});
module.controller("brandsController", function($scope, BrandService) {
$scope.brandlist = BrandService.list();
alert ($scope.brandlist);
});
</script>
The statement "alert (brands);" is not getting called. What is the issue with this code. Is m missing any thing in implementation?
$http calls are always async. Meaning, even you do a .then at your service, there is no way it will properly the resolved data back into your controller. You will have to write it in your controller.
Your Service:
module.service('BrandService', function($http) {
var brands = [];
this.getBrands = function() {
//do not need the dot then.
return $http.get('http://admin.localhost/cgi-bin/brand.pl')
}
//simply returns the brands list
this.list = function() {
return brands;
}
});
In your controller:
module.controller("brandsController", function($scope, BrandService) {
BrandService.list()
.then(function(response) {
$scope.brandlist = response.brands;
alert($scope.brandlist);
});
});
In service:
this.getBrands = function() {
$http.get('http://admin.localhost/cgi-bin/brand.pl').then(function(response) {
brands = response.brands;
alert(brands);
return brands;
});
}
In controller:
$scope.brandlist = BrandService.getBrands();
alert($scope.brandlist);

AngularJs: Controllers calls service method

I tried to create a method in the services.js :
var esServices= angular.module('esServices', []);
esServices.factory('boxItems', ['$http', function($http) {
................
}]);
esServices.factory('cartItems', ['$cookieStore', function($cookieStore) {
array = $cookieStore.get('key');
var cartItems = new function(){},
cartItems.addItem = function(itemSelected){
$cookieStore.put('key', []);
array.push(itemSelected);
$cookieStore.put('key', array);
}
}]);
in my controllers I call the service method:
esControllers.controller('esList', ['$scope','cartItems','$cookieStore',
function($scope,cartItems,$cookieStore) {
cartItems.addItem($scope.element,function(){});
};
}]);
(itemSelected is an object)
Do you Know if it is possible to pass values (objects) from Controller to Service Method in this way?
Somebody can help me!!!
esServices.factory('cartItems', ['$cookieStore', function($cookieStore) {
return {
addItem: function(itemSelected){
var array = $cookieStore.get('key');
array.push(itemSelected);
$cookieStore.put('key', array);
},
removeItem: function(){
//...
}
}
}]);
then call using
cartItems.addItem(itemSelected);
You should inject the service in the controller like
var app = angular.module('app', ['ngCookies'] );
app.factory('cartItems', ['$cookieStore', function($cookieStore) {
return {
addItems : function(){
alert('hello');
}
}
}]);
app.controller('MyController',function($scope,cartItems){
$scope.test = 'my test';
cartItems.addItems();
});
If you want to use your ugly syntax :) just return cartItems from your factory

Resources