AngularJS set var: http get - javascript

I have an angular filter set up which works great:
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.categories = store.getCategories();
$scope.products = store.getProducts();
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function(){
var categories = ['Lattes','CC Blend','Frappes'];
var products = [
{name: 'Latte machiatto',category: 'Lattes'},
{name: 'Frappe ice',category: 'Frappes'},
{name: 'Latte caramel',category: 'Lattes'},
{name: 'Frappe speculoos',category: 'Frappes'},
{name: 'Cappucino',category: 'CC Blend'},
{name: 'Filter coffee',category: 'CC Blend'},
];
return {
getCategories : function(){
return categories;
},
getProducts : function(){
return products;
}
};
});
But the var categories and var products are still hard coded so I want to retreive the needed data from my server to fill these variables. And I can't seem to get this right? I have another function where I can get the required data but I don't know how I can get these 2 in 1...?
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
});
});
So how can I properly set the var categories to the required $http.get to retreive my server data into the filter above?

I think you should be able to get rid of the hard coded block in the service and just return:
return {
getCategories: $http.get('/categories').success(function (data) {
return data;
}),
getProducts: $http.get('/products').success(function (data) {
return data;
})
}
Make sure you dependencies are setup correctly for the service though (i.e. $http):
.factory('store', function ($http) {
// The above return block here
});
And this should do the trick!

Related

Pass value from provider to controller in angularJs

I'm trying get data from db to UI. Url given via provider is getting the data.
Controller in controller DetailsProvider.getDashboardDetails() is getting null.
var appmod = angular.module('project.DetailDashboardController', []);
appmod.controller("DetailDashboardController", ['$rootScope', '$scope', '$state', 'DetailsProvider',function($rootScope, $scope, $state,DetailsProvider) {
console.log("DetailDashboardController --- ");
$scope.DetList= DetailsProvider.getDashboardDetails()
}]);
})(window, window.angular);
provider which will call the list
(function(angular) {
var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});
function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});
}
};
})(window.angular);
Thanks in advance for any kind of reply!
You should return promise from your service method and do thenable in your controller.
Root Cause : your are returning the newData which will initalized later after completing the ajax call.Before completing it,you are returning the same variable which will be always null.
In provider,
(function(angular) {
var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});
function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});
}
};
})(window.angular);
and in controller,
$scope.list = function() {
DetailsService.getDashboardDetails(function(data){
varr holdIt = data.data.DList;
});
};

How to parse many json files using AngularJS

I am trying to parse in my HTML page many JSON files:
Here is my service's code:
app.factory('myapp', ['$http', function($http) {
var tab = ['url1', 'url2', 'url3']
for(i=0; i<tab.length; i++){
return $http.get(tab[i])
.success(function(data) {
return data;
})
.error(function(err) {
return err;
}); }
}]);
In my HTML file , I only have the information of the first json file.
Here's my HTML code:
<tr>
<td>{{data.nm}}</td>
<td>{{data.cty}}</td>
<td>{{data.hse}}</td>
<td>{{data.yrs}}</td>
</tr>
Is there something to add in my HTML so I can get the information from all the json files or any other solution?
First off, you return in the first iteration in your for loop, so you only get the data for the first url. Don't return right away, assign a scope variable to your data:
Factory
app.factory('myapp', ['$http', function($http) {
function getLists() {
var tab = ['url1', 'url2', 'url3'];
var list = [];
for(i=0; i<tab.length; i++){
$http.get(tab[i])
.then(function(res) {
list.push(res.data);
});
}
return list;
}
return {
getLists: getLists
};
]);
Controller
$scope.list = myapp.getLists();
HTML
<tr ng-repeat="d in list">
<td>{{d.nm}}</td>
<td>{{d.cty}}</td>
<td>{{d.hse}}</td>
<td>{{d.yrs}}</td>
</tr>
I think what you are looking for is $q.all
I would solve the problem like this
angular.module('app').factory('myRequestsFactory',function($http, apiHost) {
var myRequestsFactory = {};
myRequestsFactory.geturl1 = function() {
return $http.get(url1);
};
myRequestsFactory.geturl2 = function() {
return $http.get(url2);
};
myRequestsFactory.geturl3 = function() {
return $http.get(url3);
};
return myRequestsFactory;
});
Then I would create an other service
angular.module('app').factory('helperService',function($q, myRequestsFactory) {
var helperService = {};
helperService.GetAll = function() {
return $q.all([
myRequestsFactory.geturl1(),
myRequestsFactory.geturl2(),
myRequestsFactory.geturl3() ]);
};
return helperService;
});
Then in my controller ..
function loadData() {
helperService.GetAll().then(
function(result) {
$scope.url1result = result[0];
$scope.url2result = result[1];
$scope.url3result = result[2];
});
},
function(error) {
}
);
}
That's how i would get access to this data

Angular - pass info from array from one controller to another

I'm having a little problem trying to pass a service within controllers.
What I'm trying to do is a shopping cart, I have a list of items and when I hit a button, those items get added to the cart, then I want to list those items in the cart in a separate page using a separate controller, so I'm trying to use a factory for the cart, but I don't know if you can set a factory object within a controller.
Here's my code, hope you can point me in the right direction.
var app = angular.module("Shop", []);
app.factory('DataService', function () {
var cart = [];
var set = function (data) {
cart = data;
}
var get = function () {
return cart;
}
});
app.controller("catalogController", function ($scope, $http) {
$scope.bookStore = {
selected: {},
books: null
};
$scope.cart = [];
$http.get("json/books.json")
.success(function (data) {
console.log(data);
$scope.bookStore.books = data;
})
.error(function (err) {
});
$scope.addToCart = function (book) {
var found = false;
$scope.cart.forEach(function (item) {
if (item.id === book.id) {
item.quantity++;
found = true;
}
});
if (!found) {
$scope.cart.push(angular.extend({
quantity: 1
}, book));
}
};
$scope.removeFromCart = function (item) {
var index = $scope.cart.indexOf(item);
$scope.cart.splice(index, 1);
};
$scope.getCartPrice = function () {
var total = 0;
$scope.cart.forEach(function (product) {
total += product.price * product.quantity;
});
return total;
};
});
app.controller("checkoutController", function ($scope, DataService) {
$scope.cart = DataService;
});
Change things a bit to something like:
app.factory('DataService', function () {
var cart = [];
return {
set: function (data) {
cart = data;
},
get: function () {
return cart;
},
add: function (item) {
cart.push(item);
}
}
});
...
app.controller("checkoutController", function ($scope, DataService) {
$scope.cart = DataService.get();
});
And then move the $http.get method and all the operations on the card in the other controller to functions in the factory and declare them on the same way as the above Dataservice.get()
You should do something like this:
A service is a singleton in angular js, that's mean you only have one instance of this class in your app.
var app = angular.module("Shop", []);
app.factory('DataService', function ($http) { // usualy your service is the one which call your API (not your controller)
var cart = null; // the cart array is set in the instance of the class as private
return{ // here you declare all the functions you want to call from outside (your controllers)
set : function (data) {
cart = data;
},
get: function(){
return cart;
},
getFromAPI = function () { // the code you have in your controller should goes here
return $http.get("json/books.json")
.success(function (data) {
console.log(data);
cart = data; //now you set you cart variable
})
.error(function (err) {
});
},
});
Then in your controllers:
app.controller("catalogController", function ($scope, DataService) { // include your service as a dependency
$scope.bookStore = {
selected: {},
books: null
};
$scope.cartInCatalogController = DataService.get(); // it will set the value of cart that's in your service to your controller's scope
if(!$scope.cartInCatalogController) {// if it's null so call the API
DataService.getFromAPI()// this function should return a promise
.success(function(data){// so call the success function
$scope.cartInCatalogController = data;
})
.error(function(error){
// do something here if you want
});
});
You can do the same in your other controller.
About the addToCard function and other stuff I let you find it by yourself.
You can start from here :)

Angular service issue -- returning an array in a service containing promises

As you can see this is my first time attempting this and I appear to be doing it incorrectly. I just want to take some code, consisting of promises and http requests, and put it in a service before the controller uses it. My goal is to simply clean up the controller so it doesn't contain all of that code.
After logging it in the last step of the controller the object appears as undefined. Also, all the requests are being made successfully. So, it's jumping through all the hoops fine so I'm guessing it must not be returning any value in the service and nothing gets passed on to the subsequent function in the controller. How can I return the 'people' array in the service after the promises have been fulfilled?
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', function ($scope, $http, dataService) {
var getPeople = function () {
return $http.get('/getpeople');
};
getPeople().then(function (response) {
dataService.compilePeople(response)
})
.then(function (people) {
console.log(people);
$scope.people = people;
});
});
myApp.service('dataService', function ($q, $http) {
this.compilePeople = function (response) {
var people = [];
names = response.data;
grandPromiseArray = [];
names.forEach(function (index) {
var name = index,
count = $q.defer(),
skills = [],
urls = '/getskillsbyname/' + name,
urlc = '/getcountbyname/' + name;
grandPromiseArray.push(
$q.all([$http.get(urls), $http.get(urlc)])
.then(function (response) {
people.push({
name: name,
skills: response[0].data,
count: response[1].data
});
})
);
});
return $q.all(grandPromiseArray).then(function () {
return people
});
}
});
You need to return the promise from compilePeople() in order for the people to be passed into the next .then() handler. so close ;)
getPeople()
.then(function (response) {
//You were missing this return
return dataService.compilePeople(response)
})
.then(function (people) {
console.log(people);
$scope.people = people;
});

How to retrieve data via asynchronous call

I am trying to use promise and service to set the data from http request.
I have something like this
angular.module('myApp').controller('productController', ['$scope', 'testService',
function($scope, testService) {
testService.getProducts().then(function(products){
console.log(products);
})
//getFirstProduct is trigger by ng-click user action.
$scope.getFirstProduct = function(){
var t = testService.getFirstProduct();
console.log(t);
}
}
]);
angular.module('myApp').service('testService', ['Product', '$q',
function(Product, $q) {
var products, firstProduct;
var getFirstProduct = function(){
return firstProduct;
}
var setFirstProduct = function(product) {
firstProduct = product;
}
var getProducts = function() {
var deferred = $q.defer();
//Product is a $resource object to send an http request
Product.query({
id: 123
}, function(result) {
setFirstProduct(result.first);
deferred.resolve(classes);
});
return deferred.promise;
}
return {
setFirstProduct: setFirstProduct,
getProducts: getProducts,
getFirstProduct: getFirstProduct
};
}
]);
I need to be able to get First product but I am not sure how to fix this. Can anyone help me about it? Thanks a lot
I see a number of errors in the code such as missing semicolons, mistyped variable/function names, and that setProducts was clobbering its variable.
Also, added $q, as mentioned by #manube
The following should work better:
angular.module('myApp').controller('productController', ['$scope', 'testService',
function($scope, testService) {
testService.getProducts().then(function(products){
console.log(products);
})
//getFirstProduct is trigger by ng-click user action.
$scope.getFirstProduct = function(){
var t = testService.getFirstProduct();
console.log(t);
}
}
]);
angular.module('myApp').service('testService', ['Product', '$q',
function(Product, $q) {
var products, firstProduct;
var getFirstProduct = function(){
return firstProduct;
}
var setFirstProduct = function(product) {
firstProduct = product;
}
var getProducts = function() {
var deferred = $q.defer();
//Product is a $resource object to send an http request
Product.query({
id: 123
}, function(result) {
setFirstProduct(result.first);
deferred.resolve(classes);
});
return deferred.promise;
}
return {
setFirstProduct: setFirstProduct,
getProducts: getProducts,
getFirstProduct: getFirstProduct
};
}
]);

Categories