1
votes

I want to create an XMLView in runtime and bind a controller to it. But I don't know how to create and instance of the controller in runtime.

Here is the code that I wrote:

var oView = sap.ui.xmlview(sViewId, {
            viewContent: sViewContent,
            controller: ?????
        });
oRouter.getViews().setView(sViewName, oView);

Here is the API that I wrote this code based on:

https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.html#.xmlview

1

1 Answers

4
votes

There are two main ways of doing it. You can either define a new controller class on the fly and then use it to instantiate a new controller instance:

var MyController = sap.ui.core.mvc.Controller.extend("MyController", {
    onInit: function() {
        // do something
    }
});
var oView = sap.ui.xmlview(sViewId, {
     viewContent: sViewContent,
     controller: new MyController()
});

Or you can use the sap.ui.controller function to define a new controller and then to obtain an instance of it:

// first define the new controller type
sap.ui.controller("MyController", {
    onInit: function() {
        // do something
    }
});
var oView = sap.ui.xmlview(sViewId, {
     viewContent: sViewContent,
     // then instantiate the controller
     controller: sap.ui.controller("MyController")
});

If inside the view XML content you reference towards the controller name, then you don't necessarily have to pass the controller instance to the sap.ui.xmlview function call. E.g. you can look at the SAPUI5 jsfiddle template: https://jsfiddle.net/nistv4n/93mx0yvt/