breken
breken

Reputation: 33

Using ng-repeat on an array within an array

I'm trying to iterate through the JSON array and through the ingredients/directions array using ng-repeat. What I have isn't working. Any advice? Thanks!

Controller:

recipeControllers.controller('DetailsController', ['$scope', '$http','$routeParams',
function($scope, $http, $routeParams) {
$http.get('app/data.json').success(function(data) {
    $scope.recipe = data;
    $scope.whichItem = $routeParams.itemId;
    $scope.recipeIngredients = recipe[whichItem].ingredients;
}]);

HTML:

<div class="recipe">
    <div class="ingredients">
        <ul>
            <li ng-repeat="item in recipeIngredients">{{recipeIngredients[whichItem].ingredients}}</li>
        </ul>
     </div> 
</div>

JSON Data:

    [
  {
    "dish":"thai_chicken_satay",
    "ingredients": ["chicken", "sauce", "stuff"],
    "directions": ["step1", "step2", "step3"]
  },

  {
    "dish":"duck_confit",
    "ingredients": ["duck", "confit", "otherstuff"],
    "directions": ["step1", "step2", "step3"]
  }

]

Upvotes: 0

Views: 102

Answers (1)

New Dev
New Dev

Reputation: 49590

If you assign $scope.recipeIngredients properly (i.e. whichItem is properly set and maps to an actual object in your JSON data), then $scope.recipeIngredients already points to an array of ingredients (e.g. ["duck", "confit", "otherstuff"]), so to iterate you simply need to do:

<li ng-repeat="item in recipeIngredients">{{item}}</li>

If you need to iterate over the entire data array of recipes, then a nested ng-repeat is needed:

<div ng-repeat="recipe in recipes">
  <div>{{recipe.dish}}</div>
  <ul>
    <li ng-repeat="item in recipe.ingredients">{{item}}</li>
  </ul>
</div>

Upvotes: 3

Related Questions