Angular Service not Saving Data - angularjs

I am trying to use a service to share data between two controllers, but the data is not saved in the service.
My Serice
angular.module('dataservice', []).
factory('DataService', function(){
var item = {};
var addItem = function(newObj) {
item = newObj;
};
var getItem = function(){
return item;
};
return {
addItem: addItem,
getItem: getItem
};
});
My Controller
angular.module('App.controllers', []).
controller('SaveController', function($scope, $routeParams, APIService,DataService){
$scope.id = $routeParams.id;
$scope.book = null;
APIService.getBook($scope.id).success(function(response){
$scope.book = response;
DataService.add($scope.book);//add to service
});
}).
controller('ReadController', function($scope,DataService){
$scope.book = null;
$scope.book = DataService.get();//get from service
})
Using chrome dev tools to inspect when i try to read the data, i just get the object definition i.e DataService = Object {}.
Thanks

First of all you have a factory in another module, so you must inject it to your main module like this:
angular.module('App.controllers', ['dataservice'])
Then, you can call that DataService factory..
Note: You're trying to access the methods add and get, but actually they're named respectively as addItem and getItem, so you should rename them.

Related

View not updating when using $controller service in angular

I have two controllers. The view is tied to the firstCtrl. I'm trying to run the function in the second one so the view is updated. Function runs but view not updated. Any ideas?
<div>{{people.length}}</div>
angular.module('myApp').controller('firstCtrl', function($scope, $http) {
var self = this;
$scope.people = [];
function getData() {
$http.get('/people').then(function(res) {
$scope.people = res.data;
});
}
getData();
$scope.getData = getData;
self.getData = function(){
$scope.getData();
};
return self;
});
angular.module('myApp').controller('secondCtrl', function( $controller, $scope, $http) {
var firstCtrl= $controller('firstCtrl', { $scope: $scope.$new() });
firstCtrl.getData(); //This runs but view is not updated above.
});
I think your code has some problem with the $scope. So instead of pass data directly in the firstCtrl. I pass a callback to getData function and assign data to $scope.people in the callback.
Here is the working Plunker:
> http://plnkr.co/edit/QznxFL

factory isnt recognized by controller

I have a controller, "ListController", which needs to be populated with server side data.
app.controller("ListController", function(){
var bar = this;
bar.venues = MyFactory.load();
}
and I wanted to get the json array from the server, so i was thinking to create a factory leveraging "$http" as such:
app.factory("MyFactory", ["$https", function($https){
var myService = {};
myService.load = function(){
$http.get("scripts/Query.php").success( function(rows){
myService.rows = rows;
return myService.rows;
};
};
return myService;
}]);
So, i was thinking that MyFactory would be able to be called from inside the app controller.
app is the same variable, of type: angular.module("BarMe", []);
The error i get in my javascript is: MyFactory is undefined
You didn't inject factory in your controller.
Try like this
app.controller("ListController", function(MyFactory){
}
More over your method has a callback direct assign won't bring you any data
Try like this
MyFactory.load().then(function(data){
bar.venues = data;
});
You also have to return $http with response from factory
myService.load = function(){
return $http.get("scripts/Query.php").success( function(rows){
return rows;
};
};

Get data from Factory

What I am trying to achieve:
Pass the parameter specId from the controller to the factory
In the factory: perform a $http.get to get JSON data
Return the JSON data to the controller
Displaying the information by assigning it to the $scope.formData
I tried many different ways but it only returns undefined. Before I created the factory I performed the $http.get directly in the controller without any issues, but now I am trying to structure the app in a better way.
Factory:
app.factory("dataFactory", function($http) {
var factory = {};
factory.getSpec = function(specId) {
return $http.get('getSpec.aspx?specId=' + specId)
};
return factory;
});
Controller
app.controller('EditSpecController', function ($scope, $stateParams, $http, dataFactory) {
$scope.specId = $stateParams.specId;
$scope.formData = [];
if($scope.specId) { //If EDIT MODE
dataFactory.getSpec($scope.specId).then(function(response) {
$scope.formData = response.data;
$scope.use_unit = response.data.use_unit;
});
}
As you noticed $http returns promise already, so you should do something more like this
factory.getSpec = function(specId) {
return $http.get('getSpec.aspx' + specId)
};
and then in controller
dataFactory.getSpec().then(function(response) {
$scope.formData = response.data;
});

How to call multiple http call to factory in angularjs?

In my project am using factory which returns list of items as per the service URL passed to that.Now i use the same factory method for all the listing items for example list of users,list of items etc.. but what happens is even i send different URLs to that factory the object is overridden.
It doesn't act as individual methods.I need to fetch different lists through different URLs using single factory and need to show in single page.
please help me with this.Thanks in advance.
this is how i would implement a service:
service:
app.factory('MyService', function ($http) {
var MyService = function () {
};
MyService.alertMe = function(message){
alert(message);
};
MyService.getUsers = function(){
return $http.get('/api/users');
};
MyService.createUser = function(user){
var data = angular.toJson(user);
return $http.post('/api/users', data);
};
return MyService;
});
usage:
app.controller('myCtrl', function($scope, MyService) {
$scope.click = function() {
MyService.alertMe('hi from service');
};
});
example: http://plnkr.co/edit/uf0kx41gsiJBLfZt0O8I?p=preview

Problems using $http inside a Service

I have a basic data Service which will be used across Controllers. But I'm having an issue grabbing some data that's been added via $http.
Service:
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
$http.get('/json').success(function(resp){
_this.dropdownData.industries = resp.industries;
});
}]);
Controller:
angular.module('core').controller('SignupController', ['$scope', '$http', '$state', 'FormService', function($scope, $http, $state, FormService) {
console.log(FormService.dropdownData); // Shows full object incl industries
console.log(FormService.dropdownData.industries); // empty object {}
}]);
How do I get FormService.dropdownData.industries in my controller?
Create a service like below
appService.factory('Service', function ($http) {
return {
getIndustries: function () {
return $http.get('/json').then(function (response) {
return response.data;
});
}
}
});
Call in controller
appCtrl.controller('personalMsgCtrl', ['$scope', 'Service', function ($scope, Service) {
$scope.Industries = Service.getIndustries();
}]);
Hope this will help
Add a method to your service and use $Http.get inside that like below
_this.getindustries = function (callback) {
return $http.get('/json').success(function(resp){
_this.dropdownData.industries = resp.industries;
callback(_this.dropdownData)
});
};
In your controller need to access it like below.
angular.module('core').controller('myController', ['$scope', 'FormService', function ($scope, FormService) {
FormService.getDropdownData(function (dropdownData) {
console.log(dropdownData); // Shows full object incl industries
console.log(dropdownData.industries); // object {}
});
} ]);
Given that your console log shows the correct object, that shows your service is functioning properly. Only one small mistake you have made here. You need to access the data attributes in your return promise.
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
$http.get('/json').success(function(resp){
//note that this is resp.data.industries, NOT resp.industries
_this.dropdownData.industries = resp.data.industries;
});
}]);
Assuming that you're data is indeed existing and there are no problems with the server, there are quite a few possible solutions
Returning a promise
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
_this.dropdownData.industries = $http.get('/json');
}]);
//Controller
FormService.industries
.then(function(res){
$scope.industries = res.industries
});
Resolving with routeProvider / ui-route
See: $http request before AngularJS app initialises?
You could also write a function to initialize the service when the application starts running. At the end of the day, it is about waiting for the data to be loaded by using a promise. If you never heard about promises before, inform yourself first.
The industries object will be populated at a later point in time when the $http call returns. In the meantime you can still bind to the reference in your view because you've preserved the reference using angular.copy. When the $http call returns, the view will automatically be updated.
It is also a good idea to allow users of your service to handle the event when the $http call returns. You can do this by saving the $promise object as a property of industries:
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
_this.dropdownData.industries.$promise = $http.get('/json').then(function(resp){
// when the ansyc call returns, populate the object,
// but preserve the reference
angular.copy( resp.data.industries, _this.dropdownData.industries);
return _this.dropdownData.industries;
});
}]);
Controller
app.controller('ctrl', function($scope, FormService){
// you can bind this to the view, even though the $http call has not returned yet
// the view will update automatically since the reference was preserved
$scope.dropdownData = FormService.dropdownData;
// alternatively, you can hook into the $http call back through the $promise
FormService.dropdownData.industries.$promise.success(function(industries) {
console.log(industries);
});
});

Resources