简体   繁体   中英

Showing images from different folders inside ng-repeat loop

I have some data (products) served from database inside ng-repeat. Every product has own id and it refers to folder with images. I want to show images for products inside loop but unfortunatelly I can't figure out how to do this with Angular.

I'm using PHP as server side API, and made function for scanning folders by id.

Inside Angular I'm trying to get those images by product id, but it works only for first product iteration. Others don't show any images.

<div ng-repeat="product in products">

  <div ng-init="scanImages( product.id )"></div>

  <div ng-repeat="image in images">
    <img ng-src="path/{{product.id}}/{{image}}" alt="">
  </div> 

</div>

In controller:

$scope.scanImages = function( productId ) {

    $http.get( 'api/images/scan/' + productId ).
    success( function( data ) {
        $scope.images = data;
    });

};

Any idea?

Each $http.get is writing to the same scope variable ($scope.images). I would perhaps make the images as an array on the product object, to keep them separated from each other. Maybe something like this:

$scope.getProducts = function() {
    $http.get('api/products').
    success( function( data ) {
        $scope.products = data;
        for(var i = 0; i < $scope.products.length; i++) {
            $scope.getImages($scope.products[i]);
        }
    });
};

$scope.getImages = function( product ) {
    $http.get( 'api/images/scan/' + product.Id ).
    success( function( data ) {
        product.images = data;
    });
};

Html:

<div ng-repeat="product in products">
  <div ng-repeat="image in product.images">
    <img ng-src="path/{{product.id}}/{{image}}" alt="">
  </div> 
</div>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM