8

我正在使用 ng-options 在我的 Angular 应用程序中打印表单的所有选项。我直接从我的数据库中获取值,它给了我一个国家列表:

<select ng-options="country.country for country in countries" ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control">

在这里,当页面加载时,选择不显示任何内容,即没有占位符,而我想打印一个像“任何地方”这样的静态值,而不必将它添加到我的“国家”列表中。

我试过这个:

<select ng-options="country.country for country in countries" ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control">
<option>Anywhere</option>
</select>

但它不工作

有谁知道如何解决这个问题?

谢谢

4

4 回答 4

18

这可能是一个较晚的帖子,但您几乎不应该在 ng-options 更适合这种情况的情况下使用 ng-repeat,因为在 ng-repeat 中创建了新的范围,因此您会有更多的开销。

您的问题的解决方案在角度文档中写得很好,您需要的看起来有点像

<select ng-options="country.country for country in countries"
        ng-model="selectedCountry"
        ng-change="updateSelectedCountry(selectedCountry)"
       class="form-control">
   <option value="" disabled>Anywhere</option>
</select>

有了这个角度,使用value=""设置一个空值并从该值之后开始迭代。

于 2015-12-30T17:36:11.383 回答
10

你总是可以这样做:

<select ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control">
    <option>Anywhere</option>
    <option ng-repeat="country.country for country in countries">{{country.country}}
    </option>
</select>

这是我的小提琴示例

希望这可以帮助!

于 2014-03-10T22:32:25.693 回答
1

我对hassassin的小提琴做了轻微的调整。这更符合ng-options预期的工作方式。例子

var myApp = angular.module('myApp', [])
    .controller('TestController', ['$scope', function ($scope) {
        $scope.data = [1,2,3];
        $scope.sel = '';
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="TestController">
    {{sel}}
    <select ng-model="sel" ng-options="val for (key , val) in data">
        <option value="">any</option>
    </select>
</div>
  </div>

于 2015-06-23T11:03:19.770 回答
0

您应该在自定义选项标签中设置value属性,在您的示例中应该是:

<select ng-options="country.country for country in countries" ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control">
  <option value='anyValueForThisOption'>Anywhere</option>
</select>
于 2018-10-28T23:21:08.977 回答