[英]AngularJS: ng-repeat with associative array
我正在尝试用关联数组实现一个简单的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>
显然,我不希望那里有空的选项,我只对最初拥有的三个选项感兴趣,但我不知道现在情况向南发展。 我是用错误的值跟踪还是数据格式不正确? 任何提示都会受到欢迎,谢谢!
PS有没有办法摆脱带有未定义值的第一个选项?
正如评论所言,答案将是使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.