簡體   English   中英

AngularJS:從數組獲取每個對象,然后進行異步調用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM