我创建的select
列表使用ng-repeat
而不是ng-options
。我遇到的问题是,一旦用户更改了值,就会有一个额外的空白列表项消失。
AngularJS - extra blank option added using ng-repeat in select tag的答案提到应该初始化所选项目以避免该问题。我做到了,但我仍然有一个空白的条目。
HTML:
<select ng-model="selectedLanguage">
<option ng-repeat="language in languages" value="{{language}}" ng-selected="selectedLanguage == language">{{language.name}}</option>
</select>
<h2>{{selectedLanguage}}</h2>
控制器:
app.controller('Ctrl', function($scope) {
$scope.languages = [{ name: "English", key: 'en' }, { name: "French", key: 'fr'}];
$scope.selectedLanguage = $scope.languages[0];
});
答案 0 :(得分:2)
你应该使用ng-options我更新你的plunkr
http://plnkr.co/edit/Iz7wFfG9l6wmQ50w2RpP
HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.2.1" data-semver="1.2.1" src="http://code.angularjs.org/1.2.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="Ctrl">
<h1>Hello Plunker!</h1>
<select ng-model="selectedLanguage" ng-options="language.name | uppercase for language in languages">
</select>
<h2>{{selectedLanguage}}</h2>
</body>
</html>
JS(无变化)
// Code goes here
var app = angular.module("app", []);
app.controller('Ctrl', function($scope) {
$scope.languages = [{ name: "English", key: 'en' }, { name: "French", key: 'fr'}];
$scope.selectedLanguage = $scope.languages[0];
});