0

Let's assume there is an array of categories. Contained within this array, for each category, there is a variable number of images. Additionally, each image has a sub-array of paths for varying sizes of each image. Listed below is an example.

$scope.categories = [
  { "id": 1, "name": "Fashion", "images": [
    { "id": 1, "paths": [
      { "id": 1, "pathThumb":"thumbnail_A.jpg"},
      { "id": 2, "pathFull":"full_size_A.jpg"}
    ]}
  ]},
  { "id": 2, "name": "Sunsets", "images": [
    { "id": 1, "paths": [
      { "id": 1, "pathThumb":"thumbnail_B.jpg"}
      { "id": 2, "pathFull":"full_size_B.jpg"}
    ]},
    { "id": 2, "paths": [
      { "id": 1, "pathThumb":"thumbnail_C.jpg"}
      { "id": 2, "pathFull":"full_size_C.jpg"}
    ]}
  ]}
];

I would like to use the AngularJS ngRepeat directive to loop through the above data to produce the following

<div class="item fashion">
  <a href="full_size_A.jpg"><img src="thumbnail_A.jpg"></a>
</div>
<div class="item sunset">
  <a href="full_size_B.jpg"><img src="thumbnail_B.jpg"></a>
</div>
<div class="item sunset">
  <a href="full_size_C.jpg"><img src="thumbnail_C.jpg"></a>
</div>

I assume it would look something like the following:

<div class="item {{category.name}}" ng-repeat="...">
  <a href="{{category.image.path.pathFull}}"><img src="{{category.image.path.pathThumb}}"></a>
</div>

I am not sure how to loop through an array with sub-array and extract the appropriate data. Any help would be greatly appreciated.

2 Answers 2

2

Use like:

<div ng-repeat="item in categories">
    <div ng-repeat="image in item.images">
        <a ng-href="{{image.paths[1].pathFull}}">
            <img ng-src="{{image.paths[0].pathThumb}}">
        </a>
    </div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

you should use a wrapper container in order to get subarray of categories..

HTML

  <div ng-repeat="category in categories">
    <div class="item {{category.name | lowercase}}" ng-repeat="image in category.images">
      <a ng-href="{{image.paths[1].path}}">
        <img ng-src="{{image.paths[0].path}}">
      </a>
    </div>
  </div>

here I used dynamic class with ng-class and using lowercase filter to get lowercase version of name string as class...

using ng-src as src attribute of img is important here because sometimes given interpolate ({{something}}) cause fail to load resource, because of data is not fecthed...

same thing for ng-href...

here is PLUNKER...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.