OpenUI5 sap.m.Input 货币格式

OpenUI5 sap.m.Input Currency Formatting

这看起来已经回答了很多次,但我似乎无法让它与我的实现一起工作。我正在尝试格式化和限制 sap.m.Input 元素中的数据。我目前有以下内容:

var ef_Amount = new sap.m.Input({
  label: 'Amount',
  textAlign: sap.ui.core.TextAlign.Right,
  value: {
    path: '/amount',
    type: 'sap.ui.model.type.Currency'
  }
});

第一个问题是它破坏了数据绑定。当我检查提交给服务器的原始数据(使用 Fiddler)时,它是一个像这样的数组:

"amount": [1234.25,null]

服务器需要一个数字,因此数组有问题。

当我使用以下内容时,绑定按预期工作但未执行任何格式设置。

var ef_Amount = new sap.m.Input({
  label: 'Amount',
  textAlign: sap.ui.core.TextAlign.Right,
  value: '{/amount}'
});

第二个问题是输入的数据不限于数字

我曾尝试使用 sap.m.MaskedInput,但我不喜欢使用占位符,因为我永远不知道要输入的数字的大小。

最后,如果当焦点放在输入字段上时,所有格式都会被删除并在失去焦点时重新格式化,那就太好了。

我是否应该考虑用 jQuery 甚至原始 Javascript 来做这件事?

感谢您的观看。

  1. 根据文档,数组输出 是正常的。所以你需要教会你的服务器接受这种格式或者在提交前预处理数据;
  2. 类型无意限制您的数据输入;
  3. 很好的功能,但是ui5不支持这个,因为Type对象不知道控件,它是像"focus"这样的事件,它只处理数据输入-输出。因此,您必须通过扩展控件或其他方式自行实现此功能。

我建议分别使用金额和货币。很可能应该只允许用户输入有效货币,因此您可以使用带有可用货币建议的组合框。

所以,在@Andrii 的大量工作和帮助之后,我设法让它工作了。主要问题是 onfocusout 破坏了模型的更新和 change 事件的触发。只需将 onfocusout 替换为 onsapfocusleave 即可解决问题。

我的自定义控件的init方法中的最终代码:

var me = this;
var numberFormat = sap.ui.core.NumberFormat.getCurrencyInstance({maxFractionDigits: 2});

me.addEventDelegate({
  onAfterRendering: function() {
    // for formatting the figures initially when loaded from the model
    me.bindValue({
      path: me.getBindingPath('value'),
      formatter: function(value) {
         return numberFormat.format(value);
      }
    });
  },
  onfocusin: function() {
    // to remove formatting when the user sets focus to the input field
    me.bindValue(me.getBindingPath('value'));
  },
  onsapfocusleave: function() {
    me.bindValue({
      path: me.getBindingPath('value'),
      formatter: function(value) {
        return numberFormat.format(value);
      }
    });
  }
});