2015-08-31 57 views
1

我有以下的情况,低于我的HTML:

<div ng-repeat="question in questions"> 
    <h2>{{question.title}}</h2> 
    <ul> 
     <li ng-repeat="choice in question.choices track by $index"> 
      <input ng-change="set(question.answer, choice)" type="checkbox" id="checkbox-{{$index}}" /> 
      <label for="checkbox-{{$index}}">{{choice}}</label> 
     </li> 
    </ul> 
</div> 

我想,当我选择该复选框,$index要在question.answers推,我已经尝试过ng-selected,ng-change但没有结果。

有人可以向我解释这是什么正确的实施?

下面我的jsfiddle。

http://jsfiddle.net/U3pVM/18292/

+0

我不太明白你在问什么。 “$ index将推在question.answers” - 即时通讯不遵循。 –

+0

所以问题有一个关键的答案,这是一个数组,我想推在这里选定的复选框的索引 – Hiero

+0

看起来像你有几个答案。 –

回答

1

所以这里是我会在做在情况:

做出的选择对象

清单让你的选择对象的列表,选择显示,如果它被选中跟踪一个布尔值。在输入域

{ 
    title:'Title', 
    choices: [ 
     {choice:"choice #1",selected:false}, 
     {choice:"choice #2",selected:false}, 
     {choice:"choice #3",selected:false}, 
     {choice:"choice #4",selected:false}], 
}, 

使用NG-模型可以再与输入字段,而不是试图推动并从列表onClick拉值的模型中使用选定的值。

这将更加清洁,如果某个项目在列表中并弹出,而不是每次点击都会推送它,您个人不必跟踪。

<input type="checkbox" ng-model="choice.selected"/> <label>{{choice.choice}}</label> 

Here is a working example

Another option that watches the list and builds an Answer list

授予在这一点上,你不会有选择值的一个干净的名单,但在需要的时候,你可以很容易地遍历您的问题/选择生成列表。

+0

谢谢你,但我真的需要布尔或什么是在question.answers。我做了ng-model = choice.answers [$ index],但是它的一组布尔值, – Hiero

+0

@Hiero请问为什么你在问题答案中需要它?你想达到什么目的? – Malkus

+0

@Hiero,我添加了另一个例子,它可以像你想要的那样建立一个列表。我不能强调,这是非常昂贵的,并且吃了很多似乎非常不必要的处理。我不会实现这一点,并选择只在需要时才生成答案列表。 – Malkus

0

这里是更新工作小提琴:

http://jsfiddle.net/U3pVM/18295/

可以使用NG单击太

<div ng-app> 
    <div ng-controller="MainCtrl"> 
    <div ng-repeat="question in questions"> 
     <h2>{{question.title}}</h2> 
     <ul> 
      <li ng-repeat="choice in question.choices track by $index"><input ng-change="set(question.answers, choice)" type="checkbox" id="checkbox-{{$index}}" /> <label for="checkbox-{{$index}}">{{choice}}</label></li> 
     </ul> 
    </div> 

+1

但如何删除当复选框取消选中,现在如果选择并取消选择它不断添加 – Hiero