我试图用关联数组实现一个简单的ng-repeat,但到目前为止还没有成功。我有以下数据:
[1: "Test", 2: "Second Test", 7: "Another Test"]
我将此保存在名为participantsList
的变量中,该变量将发送到HTML。我使用$parent
因为我有一个包装HTML页面,而且包含ng-repeat
的页面在其中呈现。这是HTML代码:
<select class="form-control" id="participant_drop_down_list" ng-model="$parent.participant_id" required>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="{{key}}">{{value}}</option>
</select>
如果我没有在声明中添加track by key
,我会得到重复的密钥错误,这是奇怪的。但是,添加后,我没有错误,但实际呈现了以下HTML:
<select class="form-control ng-pristine ng-invalid ng-invalid-required ng-touched" id="participant_drop_down_list" ng-model="$parent.participant_id" required="">
<option value="? undefined:undefined ?"></option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="0" class="ng-binding ng-scope"></option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="1" class="ng-binding ng-scope">Test</option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="2" class="ng-binding ng-scope">Second Test</option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="3" class="ng-binding ng-scope"></option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="4" class="ng-binding ng-scope"></option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="5" class="ng-binding ng-scope"></option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="6" class="ng-binding ng-scope"></option>
<option ng-repeat="(key, value) in $parent.participantsList track by key" value="7" class="ng-binding ng-scope">RT</option>
</select>
显然,我不想要那里的空选,我只对我最初的三个感兴趣,但我不知道现在南方的情况。我是通过错误的值跟踪还是数据形成不正确?欢迎任何提示,谢谢!
P.S。有没有办法摆脱未定义值的第一个选项?
答案 0 :(得分:0)
正如评论所述,答案是使用ng-options代替ng-repeat
:
<select class="form-control" id="participant_drop_down_list" ng-model="$parent.participant_id" required>
<option ng-options="key as value for (key , value) in $parent.participantsList>{{value}}</option>
</select>