Angular reading data from a json file based on ano

2019-08-09 12:21发布

问题:

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:

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>