Search code examples
xmlsapui5

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>

Solution

  • 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.