Brad Zacher
Brad Zacher

Reputation: 3243

SAPUI5: Binding controller properties to the view

I want to bind properties from my controller to the view.

in angularjs it's as simple as manipulating the $scope:

$scope.buttonProps = {
    value: 'cheese',
    disabled: 'disabled',
    onClick: function() {}
};

<custom-button disabled="buttonProps.disabled" onclick="buttonProps.onClick" value="{{buttonProps.value}}" />

however when I try to do the same in SAPUI5

sap.ui.core.mvc.Controller.extend('...', {
    buttonProps: {
        value: 'cheese',
        disabled: 'disabled',
        onClick: function() {}
    }
});

<custom-button value="{buttonProps.value}" disabled="{buttonProps.disabled}" click="buttonProps.onClick" />

it does not work - the framework doesn't seem to be able to access the properties of the "buttonProps" object.

if I, however, move the properties directly onto the controller, it works

sap.ui.core.mvc.Controller.extend('...', {
    value: 'cheese',
    disabled: 'disabled',
    onClick: function() {}
});

<custom-button value="{value}" disabled="{disabled}" click="onClick" />

but of course, this is a very disorganised way of working when you get more complex views.

I tried creating a JSONModel and binding the values via the model:

sap.ui.core.mvc.Controller.extend('...', {
    buttonProps: new sap.ui.model.json.JSONModel({
        value: 'cheese',
        disabled: 'disabled',
        onClick: function() {}
    })

    onAfterRendering: function() {
        this.byId('btn').setModel(this.buttonProps);
    }
});

<custom-button id="btn" value="{/value}" disabled="{/disabled}" click="/onClick" />

and it works for everything... except for functions.

is there a way for me to bind properties from my controller to the view?

Upvotes: 0

Views: 4288

Answers (1)

Haojie
Haojie

Reputation: 5713

UI5 follows the M-V-C paradigm and event handler is not part of data model.

The correct way to do data binding is as following:

View:

The onClick is defined as a function in the controller not in the data model.

<custom-button id="btn" value="{/value}" disabled="{/disabled}" click="onClick" />

Controller:

sap.ui.core.mvc.Controller.extend('...', {

    buttonProps: new sap.ui.model.json.JSONModel({
        value: 'cheese',
        disabled: 'disabled'
    }),

    onInit: function() {
        this.byId('btn').setModel(this.buttonProps);
    },

    onClick:function(oEvent) {

    }    

});

Upvotes: 1

Related Questions