How to display a controller variable in a sapui5 XML view?

10,361

Solution 1

Why do you want to avoid model binding? With model binding maybe not the shortest, but a typical short way would be:

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 () {
            this.myName = "Jon Doe";
            var oViewModel = new JSONModel({myName: this.myName});
            this.getView().setModel(oViewModel,"view");
        }
    });
});

and the binding in the view:

<mvc:View
    controllerName="sap.ui.demo.myApp.myController"
    xmlns="sap.m">
<Panel>
    <content>
        <Label text="{view>/myName}"/>
    </content>
</Panel>

Solution 2

I don't think it is possible to use controller variables in the view.

But there is a shortcut to this problem: just get the desired control by its id from the view after the view is rendered and set any value you want to the control:

return Controller.extend("sap.ui.demo.myApp.myController", {
    onAfterRendering: function () {
        sap.ui.getCore().byId(this.createId("<label's id>")).setText("Jon Doe");
    }
});

Of course, the "Jon Doe" text from the above example could be a variable:

var sText = "Jon Doe";
sap.ui.getCore().byId(this.createId("<label's id>")).setText(sText);
Share:
10,361
Benvorth
Author by

Benvorth

(HORACE, BK. V. Ode 3) (...) More than when, sunk in thought profound Of what the unaltering Gods require, My steward (friend but slave) brings round Logs for my fire. R. Kipling

Updated on June 28, 2022

Comments

  • Benvorth
    Benvorth almost 2 years

    How can I display a controller-variable in my sapUI5 XML-view?

    So far I have a controller:

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("sap.ui.demo.myApp.myController", {
            onInit: function () {
                this.myName = "Jon Doe";
            }
        });
    });
    

    And a XML-view:

    <mvc:View
        controllerName="sap.ui.demo.myApp.myController"
        xmlns="sap.m">
    <Panel>
        <content>
            <Label text="bind controller myName to this label"/>
        </content>
    </Panel>
    

    Is this possible without using Model-bindings? If not: what is the smartest (shortest) way to do it?