简体   繁体   中英

How can I show items specific to a selected dropdown option?

I have a dropdown list of games, and depending on which game you select, it should show a list of things I need to do for that game. My problem is getting the list to show the steps for only the currently selected game. Can this be done with ng-model, will I need to use functions, or is there an even simpler way to do this?

Also, is there any information I've included in my sample that would become redundant after utilizing provided suggestions?

HTML

<select>
    <option ng-repeat="game in things.toBeat">{{ game.title }}</option>
</select>
<ul>
    <li ng-repeat="step in things.toDo">{{ step.todo }}</li>
</ul>

JS

var games = [
    { "id" : "0", "title" : "Super Mario Bros." },
    { "id" : "1", "title" : "Pac-man" }
];

var todos = [
    { "gameID" : "0", "todo" : "Collect coins" },
    { "gameID" : "0", "todo" : "Rescue princess" },
    { "gameID" : "1", "todo" : "Eat dots" },
    { "gameID" : "1", "todo" : "Eat fruit" }
];

$scope.things = { "toBeat" : games, "toDo" : todos };

First you need to give the games select an ng-model so the second 'todo' ng-repeat can be aware of what game is selected:

<select ng-model="selectedGame">

Then you need to give the options of the selectedGame select the id value of the games so "selectedGame" will have the value of that id.

<option ng-repeat="game in things.toBeat" value="{{game.id}}">{{ game.title }}</option>

finally, you tell to the 'todo' ng-repeat to apply the filter according to the selectedGame value, matching it with the gameID field of each 'step'.

<li ng-repeat="step in things.toDo | filter: {gameID:selectedGame}">{{ step.todo }}</li>

The final code should look like this:

<select ng-model="selectedGame">
    <option ng-repeat="game in things.toBeat" value="{{game.id}}">{{ game.title }}</option>
</select>
<ul>
    <li ng-repeat="step in things.toDo | filter: {gameID:selectedGame}">{{ step.todo }}</li>
</ul>

I hope it helps

Edit:

If you want to set the default selectedGame you can use ng-init:

<select ng-model="selectedGame" ng-init="selectedGame='0'">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM