How can I implement an if-else condition in a XML-View in SAPUI5 that uses a flag (condition) from a JSONModel
?
So far I have a Controller:
JavaScript
x
20
20
1
sap.ui.define([
2
"sap/ui/core/mvc/Controller",
3
"sap/ui/model/json/JSONModel"
4
], function (Controller, JSONModel) {
5
"use strict";
6
7
return Controller.extend("sap.ui.demo.myApp.myController", {
8
onInit: function () {
9
//// set data model on view
10
var oData = {
11
title: "A cool title",
12
values: [{name: "Text 1", marketed: true}, {name: "Text 2", marketed: false}, {name: "Text 3", , marketed: true}]
13
};
14
15
var oModel = new JSONModel(oData);
16
this.getView().setModel(oModel);
17
}
18
});
19
});
20
and a View:
JavaScript
1
18
18
1
<mvc:View
2
controllerName="sap.ui.demo.myApp.myController"
3
xmlns="sap.m">
4
5
<!-- using aggregation binding -->
6
<Panel expandable="true" expanded="true" headerText="{/title}" width="100%" content="{/values}">
7
<content>
8
<Label text="{name}"/>
9
<!-- if {marketed}
10
<Label text="product is marketed"/>
11
else
12
add nothing
13
-->
14
</content>
15
</Panel>
16
17
</mvc:View>
18
Edit:
Is there a better way to do it than by implementing an overkill-feeling XML-Preprocessor?
Advertisement
Answer
OpenUI5 supports Preprocessing Instructions and Expression Binding.
With Preprocessing Instructions you can do stuff like this:
JavaScript
1
9
1
<template:if test="{marketed}">
2
<template:then>
3
<Label text="product is marketed" />
4
</template:then>
5
<template:else>
6
<Image src="path.jpg" />
7
</template:else>
8
</template:if>
9
I am not sure if the test
in the first line tests for null/not null
or true/false
. This is where the Expression Binding might be handy: it allows for complex expressions within the curly brackets:
JavaScript
1
2
1
<template:if test="{= ${marketed} === true}">
2
Edit
The following solution might be more simple, but seems a little hacky.
Embed both elements in your XML view, but toggle the visibility with complex expression binding:
JavaScript
1
3
1
<Label text="product is marketed" visible="{= ${marketed} === true}"/>
2
<Image src="path.jpg" visible="{= ${marketed} === false}"/>
3