AngularJs: Controllers calls service method - angularjs

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

Related

how to inject factory to controller

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();
};
});

i am trying to send from one controller to other contoller in angularjs but is not working

/*service */
app.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
/*first contoller */
app.controller('loginCtrl',function($scope,$location,$http,$window,sharedProperties){
$scope.submit =function(){
var username=$scope.username;
var pass=$scope.password;
sharedProperties.setProperty(username);
$location.path('/userdashboard');
$window.location.reload();
});
}
});
/*second controller*/
app.controller('empController', function($route,$scope,$http,$routeParams,sharedProperties){
$scope.getEmployees = function(){
alert( sharedProperties.getProperty());
};
};
Try this, it will work for you. :
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"></button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
function sendData($scope) {
var arrayData = [1,2,3];
$scope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $http) {
$scope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>
Service does not need to return anything. You have to assign everything in this variable. Because service will create instance by default and use that as a base object.
app.service('sharedProperties', function () {
this.property = 'First';
});
Then in controller
sharedProperties.property = $scope.username;
Had you been looking to use factory
app.factory('sharedProperties', function () {
var factory = {};
factory.property = 'Hello';
factory.setProperty = function (value) {
factory.property = value;
};
return factory;
});
Then in controller you would use it
sharedProperties.setProperty($scope.username); // Setter
$scope.var = sharedProperties.property; //getter
EDIT
Working Plnkr
You can assign members to $rootScope, which will store data globally for your app. Just inject $rootScope to each controller.
For instance...
/*first controller */
app.controller('loginCtrl',function($scope,$rootScope,$location,$http,$window,sharedProperties){
$scope.submit =function(){
var username=$scope.username;
var pass=$scope.password;
$rootScope.username = username;
$location.path('/userdashboard');
$window.location.reload();
});
}
});
This will make 'username' available to any controller that injects and consumes $rootScope.
/*second controller*/
app.controller('empController', function($route,$scope,$rootScope,$http,$routeParams,sharedProperties){
$scope.getEmployees = function(){
alert($rootScope.username);
};
};

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

Angular can not find my factory

So I created with angular a small factory to get my local json file now I wanna pass that data to my controller but it can't find the factory name and says 'unresolved variable'.
Here is the snippet of my code what I guess is relevant for now.
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
});
})();
My goal is just to console log the $scope.teams, than I can do more with the data.
you should include "dataFactory" inside your controller
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
}); })();
I believe you need to pass your factory into the controller:
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});

How to call a controller function from a service?

i have 2 controllers who are not in the same scope or have a parent child relation.
So i want to call from controlleB a function in ControllerA. In my case its a listContoller with an addItem function and i want to call this function from a addItemController somewhere else on the page after clicking submit. i know this should work with a service, but i dont know how.
app.controller("listCtrl", ["$scope", "listSvc", function ($scope, listSvc){
$scope.list.data = listSvc.load("category");
$scope.addItem = function(newitem) {
$scope.list.data.unshift(newitem);
...
}
}]);
app.controller("addItemCrtl", ["$scope", "listSvc", function ($scope, listSvc){
$scope.addItem = function() {
listSvc.addItem($scope.newItem);
}
}]);
app.service('listSvc', function() {
return{
load: function(section){
...
},
addItem: function(item){
addItem(item); <<-- call function in listController
}
}
});
UPDATE
k is this better? i put the list.data inside my service and i watch from my controller if the list change and put it on the scope from my controller that ng-repeat can do his work... is this appraoch better? or have someone better tips for me how i should do this...
app.service('listSvc', ['$http', function($http) {
var list = {};
return {
list:{
get: function () {
return list.data;
},
set: function (data) {
list.data = data;
}
},
addItem: function(item){
var response = $http.post("/api/album/"+$scope.list.section, item);
response.success(function(){
list.data.unshift(item);
console.log("yeah success added item");
}).error(function(){
console.log("buuuh something went wrong");
});
return response;
},
load: function(section){
var response = $http.get("/api/album/"+section);
response.success(function(data){
list.set(data);
list.section = section;
console.log("yeah success loaded list");
}).error(function(){
console.log("buuuh something went wrong");
});
return response;
}
};
}]);
and in my controllers i do this
app.controller("listCrtl", ["$scope", "listSvc", function ($scope, listSvc){
listSvc.load("category");
...
$scope.$watch('listSvc.list.get()', function(data) {
$scope.list.data = data;
});
...
}]);
app.controller("addItemCrtl", ["$scope", "listSvc", function ($scope, listSvc){
...
$scope.addItem = function() {
listSvc.addItem($scope.newItem);
}
...
}]);
gregor ;)
I just solved this myself! Perhaps this may help:
The function inside of my Controller:
var timeoutMsg = function() {
vm.$parent.notification = false;
};
The function inside my Service (I had to pass in $timeout as well as the name of the function from my Controller, now it works):
// original broken code:
// this.modalSend = function(vm) {
// fixed:
this.modalSend = function(vm, $timeout, timeoutMsg) {
vm.$parent.sendTransaction = function() {
// Show notification
vm.$parent.message = 'Transaction sent!';
vm.$parent.notification = true;
$timeout(timeoutMsg, 4000);
// original broken code:
// $timeout(timeoutMsg(), 4000);
};
}
var vm = $scope

Resources