如何使用表达式绑定获取数组长度?

How to get array length with Expression Binding?

如题所示,我有以下数据:

{
  "modelExample": [
    { "id": 0 },
    { "id": 1 },
    { "id": 2 }
  ]
}

JSONModel 有三个条目,本质上等同于 length 中的 3

如何通过 表达式绑定 语句获取长度?

我的尝试:

<Text text="{ ${modelExample>/}.length}"

好的,这是一个示例。单击 运行 代码片段 以查看实际效果:

sap.ui.require([
  "sap/ui/core/Core",
], Core => Core.attachInit(() => sap.ui.require([
  "sap/ui/core/Fragment",
  "sap/ui/model/json/JSONModel",
], async (Fragment, JSONModel) => {
  "use strict";
  
  // sample XML definition:
  const definition = '<ObjectStatus title="Length" text="{= ${/modelExample}.length}" class="sapMObjectStatusLarge sapUiTinyMargin" inverted="true" state="Information" xmlns="sap.m" />';
  const control = await Fragment.load({ definition });
  const model = new JSONModel({
    modelExample: [
      { id: 0, /*...*/},
      { id: 1, /*...*/},
      { id: 2, /*...*/},
    ],
  });

  control.setModel(model).placeAt("content");
})));
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody"></body>

如您所见,我正在使用 text="{= ${/modelExample}.length}" 显示数组的正确长度:

  • 如果模型被命名(例如"myModel"),它应该是{= ${myModel>/modelExample}.length}
  • 记住表达式绑定语法 requires {= (OneWay) 或 {:= (OneTime) 开头。
  • 要实际使用表达式绑定,需要将 bootstrap 配置 bindingSyntax 设置为 "complex" 或将 compatVersion 设置为 "edge",如前所述在此 。例如。在 index.html 中:
    <script id="sap-ui-bootstrap" <strong>data-sap-ui-compatversion="edge"</strong> ...>