Ken
Ken

Reputation: 3141

Conditional ngRepeat based on dropdown

I would like to display a list based on which item is selected in a dropdown.

When I use the code below, I'm getting this error: TypeError: Cannot read property 'type' of undefined

Any suggestions on how to do this right?

HTML:

<select class="form-control" ng-model="editProject.project.type" 
ng-options="project as project.type for project in editProject.options track by project.type">
</select>

<ul class="list-group">
  <li class="list-group-item" ng-repeat="benefit in editProject.foods()">{{snack}}</li>
</ul>

Controller:

.controller('EditProjectCtrl', function () {

  var editProject = this;

 editProject.options = [
    {'type': 'Fruits'},
    {'type': 'Vegetables'},
    {'type': 'Desserts'}   
];

 editProject.snacks = function() {

  if(editProject.project.type == 'Fruits') {return [
    'Grapes',
    'Oranges',
    'Apples',
  ]}

  if(editProject.project.type == 'Vegetables') {return [
    'Broccoli',
    'Spinache',
    'Kale',
  ]}

  else {return [
  'Cookies',
  'Cake', 
  'Pie']}
};

Upvotes: 0

Views: 448

Answers (1)

Michel
Michel

Reputation: 28339

You are almost there. There was a mismatch between the ng-model of the select element, and the conditions in the controller. I also replaced benefit in editProject.foods() with snack in editProject.snacks():

<select class="form-control" ng-model="editProject.project" ng-options="project as project.type for project in editProject.options track by project.type"></select>
<ul class="list-group">
    <li class="list-group-item" ng-repeat="snack in editProject.snacks()">{{snack}}</li>
</ul>

Because editProject.project is not defined until you select a project, you have to initialize it in the controller:

editProject.project = {};

See fiddle

Upvotes: 1

Related Questions