I have two tables, Category and Products with a 1-N cardinality.
What I need to do is get every product that belongs to an specific category.
This is the html table
<tr ng-repeat="category in categories">
<td>{{category.id}}</td>
<td>{{category.name}}</td>
<td>{{products[category.id]}}</td>
</tr>
And this is the controller but I don't know how to merge the categories array with the another function in order to get each object from the categories array and then make the async call with the $http service
app.controller("appController", function($scope. $http, getCategoriesService){
// Here I get all categories
$scope.categories = getCategoriesService.query();
//1. This function receive an object as a parameter and then
// make the respective request.
//2. So what I need to do is send every category from 'categories'
// array and get all products by category.
//3. I don't know how to merge this function with the array above
function(category){
$http("getProductsByCategory/"+category.id)
.success(function(data){
$scope.product[category.id];
})
.error(function(status){
console.log(status)
})
}
});
app.factory("getCategoriesService", function($resource){
return $resource("categories", {}, {
listCategories: {
method: "GET",
isArray: true
}
})
})
Any idea?
You can handle it all in your HTML with a second ng-repeat that filters the products by current category, like this:
<tr ng-repeat="category in categories">
<td>{{category.id}}</td>
<td>{{category.name}}</td>
<td>
<table>
<tr ng-repeat="product in products | filter: {categoryId: category.id}">
<td>{{ product.name}}</td>
</tr>
</table>
</td>
</tr>
Here's a working plunk .
Once you have your categories, why wouldn't you do something like:
categories.forEach(
category => getProducts(category);
);
With getProducts()
being something like:
function getProducts(category){
$http("getProductsByCategory/"+category.id)
.success(function(data){
$scope.product[category.id];
})
.error(function(status){
console.log(status)
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.