user13286 user13286 -3 years ago 97
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

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

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
template. So when you click "Cars" it would take you to a screen with 2 buttons:
. Clicking on one of those buttons would then show you the products from those sub-categories using the
template. However, if you were to click on "Trucks" from the initial screen, it would just take you directly to the
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();">

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();">{{}}</a>

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;

  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:{
    return c.category ==;
    return p.subCategory == category.category;
  }) };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download