Javascript angularJS-添加带有ng选项的静态选项

Javascript angularJS-添加带有ng选项的静态选项,javascript,angularjs,ng-options,Javascript,Angularjs,Ng Options,我正在使用ng选项打印angular应用程序中表单的所有选项。我直接从我的数据库中获取该值,该数据库为我提供了一个国家列表: <select ng-options="country.country for country in countries" ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control"> 在这里,当页面加载时,selec

我正在使用ng选项打印angular应用程序中表单的所有选项。我直接从我的数据库中获取该值,该数据库为我提供了一个国家列表:

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

在这里,当页面加载时,select不会显示任何内容,即没有占位符,而我希望打印一个静态值,如“anywhere”,而不必将其添加到我的“countries”列表中

我试过这个:

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

在任何地方
但它不起作用

有人知道如何解决这个问题吗


谢谢

您可以随时这样做:

<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>

在任何地方
{{country.country}
这是我的例子


希望这有帮助

我稍微调整了一下他的小提琴。这与
ng选项
的工作原理有点关联

var myApp=angular.module('myApp',[])
.controller('TestController',['$scope',函数($scope){
$scope.data=[1,2,3];
$scope.sel='';
}]);

{{sel}}
任何

这可能是一篇迟发的文章,但您几乎不应该使用ng repeat,因为ng选项更适合这种情况,因为新的作用域是在ng repeat中创建的,因此您会有更多的开销

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

<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=”“
设置空值,并从该值之后开始迭代。

您应该在自定义选项标记中设置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>

在任何地方

这将解决您的问题。您的答案非常好。然而,我读到ng repeat只支持字符串数据,所以如果countries是一个包含另一个对象的对象,它将不起作用。请参阅如果我们采用这种方法,我们如何预选一个选项。。?我试着将选中的国家设置为一些值,但它不起作用。也许你应该问这个问题,或者找到一个类似的问题:)很好,虽然我不能删除空白选项帮助!请在其他问题中以问题的形式提问,而不是以评论的形式提问。您可以通过将
$scope.sel
设置为等于ng选项中的任何值或默认静态选项的值来进行预选注意:
any
选项的值为
null
,在选择框中,+1 ngOptions总是比NgoRepeat好。在上面的示例中,如果删除
disabled
属性,则额外的
选项
标记将成为有效的可选选项。一个合适的例子是当你想有一个像“none”或“all”这样的选项时。确切地说,我用它来表示“all”选项,但我不能添加两个像这样的选项(“all”和“none”),如果值不同,则表示“它不起作用”。/很好的解决方案。如何使用类似的方法在迭代结束时而不是开始时添加静态选项?例如,要创建“更多”选项。@为此,您必须将“更多”选项连接到您的模型。很难想象angular能提供除此之外的任何东西。事实上,这似乎需要一点人工的努力。使用此示例并试一试-。