2015-09-29 75 views
0

我有一个游戏下拉列表,根据您选择的游戏,它应该显示我需要为该游戏做的事情列表。我的问题是获取列表来显示只有当前选择的游戏的步骤。这可以用ng-model来完成,我是否需要使用函数,还是有更简单的方法来完成这个工作?如何显示特定于所选下拉选项的项目?

另外,在我的示例中是否有任何信息会在利用提供的建议后变得多余?

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 }; 

回答

2

首先,你需要给游戏选择NG-模型,因此第二个 '待办事项' NG重复可能是意识到了什么游戏被选中:

<select ng-model="selectedGame"> 

然后,您需要给selectedGame的选项选择游戏的id值,以便“selectedGame”将具有该id的值。

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

最后,告诉到“待办事项” NG-重复根据selectedGame价值应用的过滤器,每个“步骤”的游戏ID字段匹配它。

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

最后的代码应该是这样的:

<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> 

我希望它能帮助

编辑:

如果你想设置,你可以使用NG默认selectedGame -init:

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

非常时髦,但我如何使第一个选项默认选中?我试过'ng-init =“selectedGame = selectedGame || options [0]”''''ng-init =“game = options [0]”''和'ng-init =“options [0]”' 。 –

+0

对不起,这是工作:ng-init =“selectedGame ='0'” – aFerrer

+0

我刚刚用ng-init解决方案更新了答案 – aFerrer

相关问题