在javascript中,我有两个对象数组,我正在尝试使用angular.js在html中创建下拉列表:
$scope.members=[
{name: "Paul", position: "Vocals"},
{name: "John", position: "Guitar"},
{name: "George", position: "Guitar"},
{name: "Ringo", position: "Drums"}
];
$scope.positions=[
{label: "Guitar"},
{label: "Vocals"},
{label: "Drums"}
];
HTML:
<select>
<option ng-repeat="position in positions">
{{member.position}}
</option>
</select>
当前HTML正在取消该成员的位置并将其复制3次作为下拉列表中的唯一选项。例如,在加载页面时,Ringo的位置在下拉列表中被预先选为“鼓”(这就是应该的样子)。但是当点击下拉列表时,Ringo的选项是“鼓”和“鼓”,以及“鼓”。他们应该是“鼓”,“声乐”和“吉他”。
有没有办法让所有选项都可用并在加载时预先选择正确的选项?什么是正确的指令?
答案 0 :(得分:0)
AngularJS有专门针对选择控件的指令。使用它而不是ng-repeat
https://docs.angularjs.org/api/ng/directive/ngOptions
var app = angular.module('plunker', []);
app.controller("MyCtrl", function ($scope) {
$scope.members = [
{name: "Paul", position: "Vocals", alive: true},
{name: "John", position: "Guitar", alive: false},
{name: "George", position: "Guitar", alive: false},
{name: "Ringo", position: "Drums", alive: true}
];
$scope.positions = [
{label: "Guitar"},
{label: "Vocals"},
{label: "Drums"}
];
});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="member in members">
{{member.name}}
<select ng-options="position.label as position.label for position in positions" ng-model="member.position"></select>
<input type="checkbox" ng-model="member.alive">Alive?</input>
</li>
</ul>
<pre>
{{members | json}}
</pre>
</div>
</body>
</html>
&#13;
答案 1 :(得分:0)
<select ng-model="selectedBeetle" ng-options="member as member.name for member in members"></select>
<select ng-model="selectedBeetle.position" ng-options="position.label for position in positions"></select>