Search code examples
javascriptxmlsapui5

How to get array length with Expression Binding?


As the title implies, I do have the following data:

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

The JSONModel has three entries, which essentially equates to 3 in length.

How do I get the length through an Expression Binding statement?

My Attempt:

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

Solution

  • OK, here is a sample. Click on Run code snippet to see it in action:

    globalThis.onUI5Init = () => 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://sdk.openui5.org/resources/sap-ui-core.js"
      data-sap-ui-libs="sap.ui.core,sap.m"
      data-sap-ui-on-init="onUI5Init"
      data-sap-ui-async="true"
      data-sap-ui-compat-version="edge"
      data-sap-ui-exclude-jquery-compat="true"
      data-sap-ui-xx-wait-for-theme="init"
    ></script>
    <body id="content" class="sapUiBody"></body>

    As you can see, I'm using text="{= ${/modelExample}.length}" which displays the correct length of the array:

    enter image description here

    • If the model is named ("myModel"), it should be {= ${myModel>/modelExample}.length}.
    • Expression binding syntax requires {= (OneWay) or {:= (OneTime) at the beginning.
    • To actually make use of the expression binding in UI5 1.x, either the bindingSyntax "complex" or the compatVersion "edge" needs to be set in the bootstrap config as mentioned in this post. E.g. in index.html:
      <script id="sap-ui-bootstrap" src="..." data-sap-ui-compat-version="edge" ...>