-1

Trying to use ng-repeat for an array of strings. I have 2 scenarios, 1 where it works, the other where it does not. My question is why doesn't it work?

The family types are are displayed accordingly in this situation: working

<div ng-controller="productsController as product">
    <ul>
        <li ng-repeat="family in product.families | orderBy: 'category'">
            <ul>
                <li ng-repeat="type in family.types">{{type}}</li>
            </ul>
        </li>
    </ul>
</div>

However, in this situation they are not being displayed: not-working why?

<div ng-controller="productsController as product">
    <ul>
        <li ng-repeat="family in product.families | orderBy: 'category'">
        </li>
    </ul>
    <ul>
        <li ng-repeat="type in product.families.types">{{type}}</li>
    </ul>
</div>

What would be the proper way to repeat types in this situation?

JSON

"families": [
    {
      "category": "Tablets",
      "types": ["type1", "type2", "type3", ...]
    }
]
Adjit
  • 10,134
  • 12
  • 53
  • 98
  • What is the content of `product.families`? –  Sep 28 '15 at 16:30
  • any error in console? – Lucas Sep 28 '15 at 16:30
  • 1
    In your "not-working" example, you are trying to itrate over `product.families.types` - this does not work, as `families` most probably is an array, which doesn't have a `types` property. If you want to display all types, you need to use the first approach. Or you build an array containing all types, over which you can then iterate. – PzYon Sep 28 '15 at 16:31

1 Answers1

1

product.families is an array. An array doesn't have any property named types.

The appropriate way would be to extract an array in the controller that would contain all the types of all the families as a single array, and to iterate over the types contained in that single array:

var typeArrays = $scope.families.map(function(family) {
    return family.types;
});
$scope.allTypes = [].concat.apply([], typeArrays);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Would you be able to show me an example of how to do that? – Adjit Sep 28 '15 at 16:40
  • I have updated my answer. See http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript for an explanation of the last line. – JB Nizet Sep 28 '15 at 16:46
  • Maybe you might also need a check in order to have only a distinct list of `type`s (no duplicates). But maybe this is already the case if each `family` has it's own, unique `type`s. And if they can have same values, then you should consider using `track by $index` in `ng-repeat`. – PzYon Sep 28 '15 at 16:54