Show TOC

ControllersLocate this document in the navigation structure

SAPUI5 uses the controller to separate the view logic from the model logic.

The methods used for controlling the data flow are implemented in the controller.

You define a simple controller without functions as follows:

	sap.ui.controller("sap.hcm.Address", {
   // controller logic goes here
});

The string in quotes specifies the controller name. The controller file is then named Address.controller.js.

Note

The suffix .controller.js is mandatory for controllers.

Lifecycle Hooks

SAPUI5 provides predefined lifecycle hooks for implementation. You can add event handlers or other functions to the controller and the controller can fire events, for which other controllers or entities can register.

SAPUI5 provides the following lifecycle hooks:

  • onInit(): Called when a view is instantiated and its controls (if available) have already been created; used to modify the view before it is displayed to bind event handlers and do other one-time initialization

  • onExit(): Called when the view is destroyed; used to free resources and finalize activities

  • onAfterRendering(): Called when the view has been rendered and, therefore, its HTML is part of the document; used to do post-rendering manipulations of the HTML. SAPUI5 controls get this hook after being rendered.

  • onBeforeRendering(): Invoked before the controller view is re-rendered and not before the first rendering; use onInit() for invoking the hook before the first rendering

Note For controllers without a view, no lifecycle hooks are called.
Example
sap.ui.controller("sap.hcm.Address", {
   onInit: function() {
      this.counter = 0;
   }
});
Event Handlers and Other Functions

In addition to lifecycle hooks, a controller can define additional methods that serve as event handlers or additional functionality offered by the controller.

Example
sap.ui.controller("sap.hcm.Address", {
   increaseCounter: function() {
      this.counter++;
   }
});
API Reference