In this step, we replace the text with a button and show the “Hello World” message when the button is pressed. The handling of the button's press
event is implemented in the controller of the view.
A Say Hello button is added
You can access the live preview by clicking on this link: 🔗 Live Preview of Step 5.
To download the solution for this step as a zip file, just choose the link here: 📥 Download Solution for Step 5.
First of all, we need a conroller for our app view that defines how the view should react to user inputs, such as a button press event.
We create a new folder called controller
inside the webapp
folder. This folder will hold all our controller files. Inside the controller
folder, we create a new file called App.view.xml
. We define the app controller in its own file by extending the OpenUI5-provided sap/ui/core/mvc/Controller
. In the beginning, it holds only a single function called onShowHello
that shows an alert with the static text "Hello World".
import Controller from "sap/ui/core/mvc/Controller";
/**
* @name ui5.walkthrough.controller.App
*/
export default class AppController extends Controller {
onShowHello(): void {
// show a native JavaScript alert
alert("Hello World");
}
};
📝 Note:
The comment@name ui5.walkthrough.controller.App
is a JSDoc comment that names this controller. It can be used by documentation generators and IDEs to provide more information about this class.
To connect our controller with the view, we need to specify the name of our newly created controller in the controllerName
attribute of the root node. This allows us to access the event handlers and other functionalities defined in the controller. The name should be a module path, which is the location of the controller file.
In addition, we replace the <text>
tag with a <button>
tag. We set the text
attribute of the button to the static value "Say Hello" and assign the onShowHello
event from our app controller to the press
attribute of the button. To indicate that the press event handler is located in the controller of the view and not in the Global Namespace, we prefix the handler name with a dot (.
) character.
<mvc:View
controllerName="ui5.walkthrough.controller.App"
xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc">
<Button
text="Say Hello"
press=".onShowHello"/>
</mvc:View>
A view does not necessarily need an explicitly assigned controller. You do not have to create a controller if the view is just displaying information and no additional functionality is required. If a controller is specified, it is instantiated after the view is loaded.
-
Controller names are capitalized
-
All controllers are stored in the
controller
folder -
Controllers carry the same name as the related view (if there is a 1:1 relationship)
-
Event handlers are prefixed with
on
-
Controller names always end with
*.controller.js
(in JavaScript) or*.controller.ts
(in TypeScript)
Next: Step 6: Modules
Previous: Step 4: XML Views
Related Information