In the webapp > controller
folder, open theDetail.controller.js
file.
First, you need to add some new resources to the controller. This controller will need access to the browser history, so add the routing history resource. Also, you will need access to JSONModel
in this controller. Add these resources to the define array.
,
"sap/ui/core/routing/History",
"sap/ui/model/json/JSONModel"
To make the resources available in the controller, add the following parameters to the controller function definition.
, History, JSONModel
Delete all the commented code in the controller. You will define a new set of functions.
Create a new onInit
(#1) function. This function needs to create a new JSONModel
to hold the message details, and the model needs to be bound to the view. Additionally, you need to get the router for this view and use it to match the data passed in the messagePath
argument.
onInit: function () {
var oModel = new JSONModel();
this.getView().setModel(oModel, "message");
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.getRoute("detail").attachMatched(this._onRouteMatched, this);
},
Add a _onRouteMatched
(#2) function that is called from the onInit
function. The _onRouteMatched
function has a parameter of oEvent
. This function will bind the data for the message based on the argument messagePath
from the main view. It will bind it to the message model you created in the onInit
function.
_onRouteMatched: function (oEvent) {
this.getView().bindElement({
path: "/" + oEvent.getParameter("arguments").messagePath,
model: "message"
});
},
Finally, add in a onNavBack
(#3) function that will allow you to navigate back to the main view (View1
) from the Detail view. The back navigation uses the browser history to go back to the page you were previous on. If the browser history cannot be accessed, you will be navigated back to the View1
view without any of the history of the previous page.
onNavBack: function () {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("view1", true);
}
}
SAVE your changes.