[英]Angular JS: default value in select menu with ng-repeat options
I have tried to follow the examples on the Angular 1.4.12 docs and what I've found here, still I cannot set a default value for a select menu. 我试图按照Angular 1.4.12文档中的示例以及在这里找到的内容进行操作,但仍然无法为选择菜单设置默认值。
My html (using controller as
of mob
): 我的html(使用mob
controller as
):
<select name="userCurrencyType"
ng-model="mob.currencyType"
ng-options="s.name + ' - ' + s.code for s in mob.currencyTypes"></select>
Which correctly gives me a menu like: 正确地给我一个像这样的菜单:
Where my json is an array of objects: 我的json是对象数组:
[{ "code": "USD", "name": "United States Dollar" },
{ "code": "GBP", "name": "United Kingdom Pound" }...]
I want the default menu item to be the first item (USD). 我希望默认菜单项成为第一项(USD)。 I have tried setting the ng-model
to mob.currencyType
and setting this in the controller both like: 我尝试将ng-model
设置为mob.currencyType
并在控制器mob.currencyType
其设置为:
_this.currencyType = _this.currencyTypes[0];
and 和
_this.currencyType = { "code": "USD", "name": "United States Dollar" }
Neither approach gives me a default value set. 两种方法都没有给我默认值集。 What am I missing? 我想念什么?
After some good suggestions from other users, and some experimenting, it would seem the problem was my data service call was not returning a promise: 经过其他用户的一些好的建议和一些试验之后,似乎问题出在我的数据服务调用没有返回承诺:
_this.currencyTypes = MockDataFactory.query({ filename: 'currency_codes' });
So I added 所以我加了
_this.currencyTypes.$promise.then(function () {
init();
});
And then 接着
function init () {
_this.currencyType = _this.currencyTypes[0];
}
What you have is fine, just include a track by: 您所拥有的都很好,只需添加以下内容的跟踪:
<select name="userCurrencyType"
ng-model="mob.currencyType"
ng-options="s.name + ' - ' + s.code for s in mob.currencyTypes track by s.code"></select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.