Benvorth
Benvorth

Reputation: 7722

How to iterate over a JSONModel in a sapUI XML-View?

How can I build a XML-View in SapUI5 that iterates over all elements in a JSONModel?

So far I have a Controller:

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel"
], function (Controller, JSONModel) {
    "use strict";

    return Controller.extend("sap.ui.demo.myApp.myController", {
        onInit: function () {
            //// set data model on view
            var oData = {
                title: "A cool title",
                values: [{name: "Text 1"}, {name: "Text 2"}, {name: "Text 3"}]
            };
            var oModel = new JSONModel(oData);
            this.getView().setModel(oModel);
        }
    });
});

and a View:

<mvc:View
        controllerName="sap.ui.demo.myApp.myController"
        xmlns="sap.m"
>
    <Panel expandable="true" expanded="true" headerText="{/title}" width="100%">
        <content>
            <!-- how to iterate over {/values} ? -->
        </content>
    </Panel>

</mvc:View>

Upvotes: 4

Views: 5760

Answers (2)

Jpsy
Jpsy

Reputation: 20892

Just to reiterate:
You can use aggregation binding on all controls that have aggregations.
One of the simplest ways to output array data as a repeated Text control is a VBox:

<VBox items="{MyModel>/MyArrayProp}">
  <items>
    <Text text="{MyModel>FieldWithinMyArrayProp}" />
  </items>
</VBox >

Upvotes: 1

schnoedel
schnoedel

Reputation: 3948

you can use aggregation binding to bind the content of the panel to your values array. You have to add an template control that will be cloned for each array item. Use relative binding paths within the template to access the properties of the particular array item.

<mvc:View
    controllerName="sap.ui.demo.myApp.myController"
    xmlns="sap.m"
>
    <Panel expandable="true" expanded="true" headerText="{/title}" width="100%" content="{/values}">
        <content>
            <!-- give the template control which will be cloned for each entry in your array -->
            <Label text="{name}"/>
        </content>
    </Panel>
</mvc:View>

I hope this gives you some help.

Upvotes: 6

Related Questions