[英]AngularJS : Get each object from array and then make async calls
我有两个表,类别和具有1-N基数的产品。
我需要做的是获取属于特定类别的每个产品。
这是html表
<tr ng-repeat="category in categories">
<td>{{category.id}}</td>
<td>{{category.name}}</td>
<td>{{products[category.id]}}</td>
</tr>
这是控制器,但我不知道怎么才能得到从类别阵列中的每个对象,然后使用$ http服务的异步调用的类别阵列的另一个功能合并
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
}
})
})
任何想法?
您可以使用第二个ng-repeat在HTML中处理所有内容,该ng-repeat按当前类别过滤产品,如下所示:
<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>
这是工作中的小伙伴 。
拥有类别后,为什么不执行以下操作:
categories.forEach(
category => getProducts(category);
);
与getProducts()
类似:
function getProducts(category){
$http("getProductsByCategory/"+category.id)
.success(function(data){
$scope.product[category.id];
})
.error(function(status){
console.log(status)
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.