user13286 user13286 - 1 year ago 62
AngularJS Question

How to handle conditional sub-category in AngularJS product gallery

Just starting out learning AngularJS and decided to mock up a basic product gallery using what I've learned so far and I've hit a roadblock. Currently I have a simple product gallery with 3 templates(category listing, products in category listing and product overview). What I would like to do is set up some sort of conditional, where if the products in a selected category have a sub-category, it displays a list of sub-categories using the

category-list
template. If they don't have a sub-category it just goes straight to the
product-list
template.

I have created this Plunker showing where I am at so far.

In the above example, if someone clicks on "Cars" I want it to then show a listing of sub-categories using the
category-list
template. So when you click "Cars" it would take you to a screen with 2 buttons:
4-door
and
2-door
. Clicking on one of those buttons would then show you the products from those sub-categories using the
product-list
template. However, if you were to click on "Trucks" from the initial screen, it would just take you directly to the
product-list
template since the trucks don't have sub-categories.

Here is my category-list template:

<section id="categories" ng-hide="productsVisible">
<div ng-repeat="product in vm.products" class="category">
<div ng-click="vm.selectCategory(product); showProducts();">
<button>{{product.category}}</button>
</div>
</div>
</section>


And here is my product-list template:

<section id="products" ng-show="productsVisible">
<div ng-repeat="product in vm.selectedCategory.items" class="product">
<a href ng-click="vm.selectProduct(product); showResults();">{{product.name}}</a>
</div>
</section>

Answer Source

See my updated plunker

Basically, you need to extend the selectCategory method by grouping the sub-categories and checking whether we're about to enter this sub-category in subsequent click. Like this:

vm.selectCategory = function(category) {
  var subCats = [],
      map = {};

  if (category.items && !category.items[0].subCategory){
    vm.selectedCategory = category;
    vm.inSubCat = true;
    return;
  }

  vm.inSubCat = !category.items;
  if (category.items) category.items.forEach(function(e){
    if (!map[e.subCategory]) subCats.push({category: e.subCategory, name: category.category});
    map[e.subCategory] = true;
  });
  vm.products = subCats;

  if (vm.inSubCat) vm.selectedCategory = {items: vm.data.filter(function(c){
    return c.category == category.name;
  })[0].items.filter(function(p){
    return p.subCategory == category.category;
  }) };
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download