AngularJS下拉(ng-选项)不绑定 - 字符串到对象(初始选择)

Sho*_*lad 5 angularjs ng-options

我将从服务器检索到的数据绑定到下拉列表时遇到问题.我认为的主要问题是比较是在不同的对象类型上完成的.

例如:1.从服务器返回的对象包含货币代码字符串.我们希望将其绑定到下拉列表中的项目

"baseCurrencyCode":"GBP"
Run Code Online (Sandbox Code Playgroud)
  1. 视图模型返回货币列表.这些货币将作为具有不同属性的货币对象列表返回

    {"currencies":[{"id":1,"rateId":0,"abbreviation":"AFN","description":"Afghani","rate":0.0,"rateDescription":null,"languageCode":"en-gb","isDefault":true,"fullDescription":"AFN - Afghani - ","shortDescription":"AFN - Afghani"}}
    
    Run Code Online (Sandbox Code Playgroud)

等等

目前,我通过编写一个函数来完成列表中每个项目的每个属性,找到我们希望比较的正确属性 - 进行比较,然后返回初始选择.

在调用我的保存方法时,我需要手动将货币缩写绑定到我希望返回服务器的对象.

当然必须有更好的方法来做到这一点?

我的一些代码供参考..

<select ng-model="selectedCurrency" ng-options="currency.shortDescription for currency in viewModel.currencies"></select>

// Call to my custom method..List, PropertyName, value to compare 
$scope.selectedCurrency = InitialiseDropdown($scope.viewModel.currencies, "abbreviation", $scope.updatedObject.baseCurrencyCode);

// Code executed when saving - to bind the currency to the updated object
$scope.updatedObject.baseCurrencyCode = $scope.selectedCurrency.abbreviation;
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏!

编辑 对不起,如果我不够清楚..总结..

这里的主要问题是绑定到下拉和初始选择.

我们正在更新的对象包含货币缩写的参数(字符串).

我们从中选择的列表是货币对象列表.由于这些是两种不同的对象类型,我无法插入角度2路绑定,并且在初始检索和保存时编写了一些代码来执行此操作.

解决此问题的最简单方法是在检索中返回货币对象而不是缩写的简单字符串,但这不是一个选项.

有没有更好的方法在不同的对象类型上启用双向绑定?

再次感谢

gka*_*pak 16

目前尚不清楚问题是什么,但您可以通过绑定<select>到当前选定的货币对象来节省一些工作(因此您不必在以后查找).
select+ ngOptions允许您在显示另一个值时绑定到一个值,使用以下语法:

<select ng-model="selectedCurrency"
        ng-options="currency as currency.shortDescription
                    for currency in viewModel.currencies">
</select>
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,$scope.selectedCurrency将绑定到整个currency对象,但currency.shortDescription会在下拉列表中显示.


另见这个简短的演示.


更新:

如果你不需要绑定到整个货币的对象,而只是绑定updatedObjectbaseCurrencyCode属性来选择的(在下拉列表)货币的缩写,你可以做这样的:

<!-- In the VIEW -->
<select ng-model="updatedObject.baseCurrencyCode"
        ng-options="c.abbreviation as c.shortDescription
                    for c in currencies">
</select>

// In the CONTROLLER
$scope.currencies = [...];
$scope.updatedObject = {
    ...
    baseCurrencyCode: <baseCurrencyCodeFromServer>
};
Run Code Online (Sandbox Code Playgroud)

另见简短的演示.