1

I'm new to angular and have run into a scenario where I don't know the best way to setup this code.

I have 2 JSON files:

images.json

{
    "imageName":        "example.jpg",
    "imageTags":        ["fun","work","utility"]
    "productID":        ["item1","item3"]
}

products.json

{
    "productID":        "item1",
    "productName":      "Staple Gun",
    "productURL":       "Staple-Gun.htm"
}

I don't have any code yet, I'm really trying to make sure I build this properly first.

My goal is to pull images based on tags, so I put a filter on the first ng-repeat portion. This portion works well. But I want to be able to link to the products that are in the images. The easiest thing I found was to do a ng-repeat with the productID as a filter, but if I am pulling 50 photos and each photo has 2 items, that is a ton of repeats. It seems to me that this would require a ton of resources. Is this the best way or is there a better way to handle this?

Code example:

<div ng-repeat="photo in photos | filter: 'fun'">
   <img ng-src="{{ photo.imageName }}">
   <span>Products In This Image</span>
   <div ng-repeat="product in products | filter: photo.productID">
       <a ng-href="{{ product.productURL }}" title="{{ product.productName }}">{{ product.productName }}</a>
   </div>
</div>

1 Answer 1

1

A simple mapping of the products to an object that uses the productID as keys would be much more efficient

$scope.product_map = {};
products.forEach(function(item) {
  $scope.product_map[item.productID] = item
});

Will produce:

{
  "item1": {
    "productID": "item1",
    "productName": "Staple Gun",
    "productURL": "Staple-Gun.htm"
  }
}

This means instead of having to filter a whole array each time you need to look up a product you can simply do:

var productNeeded = $scope.product_map['item1'];

In the view this would translate to:

<div ng-repeat="photo in photos | filter: 'fun'">
   <img ng-src="{{ photo.imageName }}">
   <span>Products In This Image</span>
    <!-- iterate small array of productID's in photo object -->
   <div ng-repeat="id in photo.productID">
       <!-- product_map[id] is a single object reference -->
       <a ng-href="{{ product_map[id].productURL }}" title="{{ product_map[id].productName }}">{{ product_map[id].productName }}</a>
   </div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. I figured there had to be a better way to reference the list without having to reload the list every single time. My json files are large and this should speed things up quite a bit.

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.