首页 > 解决方案 > 模型属性被视为对象而不是 formatOptions 中的字符串

问题描述

我有一个包含标签和输入组件的片段。它的值大多是静态设置的,并且按预期工作:

<Label text="Customer" />
<Input
  value="John Smith"
  editable="true"
  change=".liveChangeVehicleGrossPrice"
/>
<Label text="Price" />
<Input
  editable="true"
  change=".liveChangeVehicleGrossPrice"
  value="{
    parts: [
      'P02_Model>/VehicleGrossPrice',
      'valuta>/convert'
    ],
    type: 'sap.ui.model.type.Currency',
    formatOptions: {
      showMeasure: false
    }
  }"
/>

现在我在控制器中创建了一个模型,其中包含要在输入组件中使用的值:一个值(客户)要添加到客户名称字段中,两个属性(groupingSeparatordecimalSeparator)用于格式化货币:

var json = {
  "groupingSeparator": " ",
  "decimalSeparator": ",",
  "customer": "John Wayne",
};
var model = new JSONModel(json);
this.getView().setModel(model, "P02_Model");

创建此模型后,我修改片段以使用这些值:

<Label text="Customer" />
<Input
  editable="true"
  change=".liveChangeVehicleGrossPrice"
  value="{P02_Model>/customer}"
/>
<Label text="Price" />
<Input
  editable="true"
  change=".liveChangeVehicleGrossPrice"
  value="{
    parts: [
      'P02_Model>/VehicleGrossPrice',
      'valuta>/convert'
    ],
    type: 'sap.ui.model.type.Currency',
    formatOptions: {
      showMeasure: false,
      groupingSeparator: {P02_Model>/groupingSeparator},
      decimalSeparator: {P02_Model>/decimalSeparator}
    }
  }"
/>

问题是当页面加载时,名称John Wayne在关联输入中正确映射,但包含货币的输入会有

112[对象对象]323[对象对象]2

而不是112 323,2.

groupingSeparator不知何故,与和关联的两个值decimalSeparator是字符串,被视为对象。为什么?

标签: sapui5

解决方案


为什么?

这是因为绑定信息对象不是 ManagedObject,而是一个不支持绑定功能的简单对象。您必须在 JS 中执行此操作。

<Input id="myInput" />
onInit: function() {
  // ...    
  const model = this.getView().getModel("P02_Model");
  this.byId("myInput").bindValue({
    parts: [
      "P02_Model>/VehicleGrossPrice",
      "valuta>/convert"
    ],
    type: this.createCurrencyType()
  });
},

onModelDataChanged: function() {
  this.byId("myInput").getBinding("value").setType(this.createCurrencyType());
},

createCurrencyType: function() {
  return new CurrencyType({ // required "sap/ui/model/type/Currency"
    groupingSeparator: model.getProperty("/groupingSeparator"),
    decimalSeparator: model.getProperty("/decimalSeparator")
  });
},

推荐阅读