Search code examples
angularjsstoreangularjs-ng-repeat

How get a label from a store in Angular while repeat another store


I've two stores in my controller:

$scope.categoryStore = [{id: 1, label: "A"}, {id: 2, label: "B"}, {id: 3, label: "C"}];

$scope.collectionStore = [{id: 1, categoryId: 1, name: "Test"}, {id: 1, categoryId: 2, name: "Test2"}];

In my view I have a ng-repeat for the collectionStore. Now I want to display the label of the categoryStore instead of the categoryId.

<tr ng-repeat="item in collectionStore">
   <td>{{item.id}}</td>
   <td>{{item.categoryid}} <!-- this would be the label --></td>
   <td>{{item.name}}</td>
</tr>

Solution

  • My suggestion is to create a function to handle this and use the $filter within that function.

    In your view:

    <tr ng-repeat="item in collectionStore">
       <td>{{item.id}}</td>
       <td>{{getCategoryLabel(item.categoryId)}}</td> <!-- handle this with a function -->
       <td>{{item.name}}</td>
    </tr>
    

    Then in your controller:

    $scope.getCategoryLabel = function(categoryId) {
        var category = $filter('filter')($scope.categoryStore, { id: categoryId }, true);
    
        if (category.length) return category[0].label;
    }