Angular reading data from a json file based on another json file

北战南征 提交于 2019-12-11 12:32:15

问题


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>


来源:https://stackoverflow.com/questions/35184435/angular-reading-data-from-a-json-file-based-on-another-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!