antonyboom antonyboom - 5 months ago 13
Javascript Question

bind data from different requests in ng-repeat

On my page I'm rendering panel with 6 categories. The categories come from api call:

var getCategories = function (customUrl) {

$http.get(customUrl).then(function success(response) {
$scope.categories = response.data;
// console.log($scope.categories);
// ****
},
function error(response) {
console.log("It has happened error in categories response", response)
});
};


inside of this request I have angular.forEach loop, where I'm sending api request for each category separately

angular.forEach($scope.categories, function (category) {

var queryString = '?categoryId=',
url = urlData + queryString;

var getArrayLength = function(url){
$http.get(url)
.then(function success(response) {
$scope.getLength = response.data;
console.log($scope.getLength)

}, function error(response) {
console.log("error in getting length", response)
});
};

getArrayLength(url + category.id);

category.selected = $scope.selectedAllCat;
});


for now everything looks good, console log for
$scope.getLength
returns 6 different arrays
$scope.getLength.length
returns length for those arrays

Now I'm rendering table on my page like

<div class="panel-body">
<table class="table">
<tr>
<td class="col-md-1"><input type="checkbox"
ng-model="selectedAllCat"
ng-click="selectAllCat()">&nbsp;</td>
<td class="col-md-9">All</td>
<td class="col-md-2">
{{ initialDataLength.length }}
</td>
</tr>
<tr ng-repeat="category in categories | orderBy : 'id' ">
<td class="col-md-1">
<input type="checkbox"
ng-model="category.selected"
ng-click="updateFilter(category.id)">&nbsp;
</td>
<td class="col-md-9">{{ category.name }}</td>
<td class="col-md-2">
{{ getLength.length }}
</td>
</tr>
</table>




That's my trouble point. How could I bind array's length with category name? Now it's showing only same length across each category name. Thank you in advance

Answer

You could create an object mapping category ids with length, and load the values after each request.

$scope.categoryLenghts = {};
angular.forEach($scope.categories, function (category) {

    var queryString = '?categoryId=',
        url = urlData + queryString;

    var getArrayLength = function(url){
       $http.get(url)
           .then(function success(response) {
               $scope.getLength = response.data;
               $scope.categoryLengths[category.id] = response.data // Save category length
               console.log($scope.getLength)

            }, function error(response) {
                console.log("error in getting length", response)
            });
    };
    getArrayLength(url + category.id);

    category.selected = $scope.selectedAllCat;
});

Then render it like this:

<td class="col-md-9">{{ category.name }}</td>
<td class="col-md-2">{{ categoryLengths[category.id] }}</td>
Comments