[英]angularjs ng-option with ng-change
I have this model that looks something like this: 我有一个看起来像这样的模型:
{
id: 1,
country: {
code: 'GB',
name: ''
}
}
The country code is stored in the database, but the name is not. 国家/地区代码存储在数据库中,但名称不存在。 However, there is another application that requires the country name rather than the code.... So, when editing this model I have a dropdown that has a list of countries that has both code and name . 但是,还有另一个应用程序需要国家名称而不是代码。...因此,在编辑此模型时,我有一个下拉列表,其中包含具有代码和名称的国家/地区列表。 I set the ng-options up like this: 我像这样设置ng-options:
ng-options="item.code as item.name for item in controller.countries"
I did this so that the country would be pre-populated with my current code. 我这样做是为了使该国家/地区可以预先填充我当前的代码。 The issue is, I want to set the name when someone chooses a different country. 问题是,当有人选择其他国家/地区时,我想设置名称 。 I tried doing it like this: 我尝试这样做:
ng-change="controller.setCodeAndName(controller.model.country, item)"
and the method just looks like this: 该方法如下所示:
setCodeAndName: function (model, item) {
console.log(item);
model.code = item.value;
model.fullName = item.description;
},
However, this does not work because item is undefined. 但是,这不起作用,因为未定义item 。 I know this is because item (which is supposed to be the current selected item) has not been passed to the method. 我知道这是因为项目 (应该是当前选定的项目)尚未传递给方法。 Does anyone know of a way to fix my issue so that a country is pre-populated based on the code alone and when it changes it will add the name to the object? 有谁知道一种解决我的问题的方法,以便仅根据代码预先填充一个国家/地区,当它更改时,会将名称添加到对象中?
You also need an ngModel
on that select - I'd also recommend just using the entire object as the model assignment - so your select
ends up looking like: 您还需要在该选择上使用ngModel
我也建议您仅使用整个对象作为模型分配-这样您的select
最终看起来像:
<select
ng-model="selectedItem"
ng-options="item as item.name for item in controller.countries"
ng-change="controller.setCodeAndName(selectedItem)"
</select>
And your method: 而你的方法:
setCodeAndName: function (item) {
console.log(item);
model.code = item.value;
model.fullName = item.description;
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.