cancel
Showing results for 
Search instead for 
Did you mean: 

UI5 Set/Get a Global model

gary_king2
Participant

I have read a few articles on using a Global model, and, there seem to be a number of ways of doing this, some right and some wrong. I'm avoiding defining my model in manifest at present and opting to define it directly in the component.js. The code I'm using is as follows:

Within the component.js onInit:

//var oModel1 = new sap.ui.model.json.JSONModel("model/Testmodel.json");
var oData = { Test : { name : "World" }	};
var oModel1 = new sap.ui.model.json.JSONModel(oData);
sap.ui.getCore().setModel(oModel1,"oModelTest");

And in my View Controller.js I have the following code within the onInit function:

var oModel = sap.ui.getCore().getModel("oModelTest");

However, oModel is showing as undefined when monitoring in debug. It does not error though. I have also tried using the variable oModel1 as someone mentioned that name should be the same at both ends of the set/get. But alas the same issue.

Someone mentioned that ideally we should not use the core to set/get the global model. I am intrigued to see how I can get this working, and if possible without using the core.

If anyone has this working I would greatly appreciate some demonstration code.

Best regards

View Entire Topic
karthikarjun
Active Contributor
0 Kudos

use this.getView().setModel(ModelName, "ModelName")

gary_king2
Participant
0 Kudos

Yes, I have used that within the component, but, when I then attempt to retrieve the model in the controller using .getModel it does not retrieve anything.

We have also tried to define a model (global) within the manifest, but we seem to hit the same issue that we always hit whenever we attempt to load a json file, in that it fails. Well, it does not fail, but gives a 404 error. We've tried:

oModel1.loadData("model/Testmodel.json");
oModel1.loadData("Testmodel.json");
var oModel1 = new sap.ui.model.json.JSONModel("Testmodel.json";
var oModel1 = new sap.ui.model.json.JSONModel("model/Testmodel.json");

And obviously my json file is in the model subdirectory and called Testmodel.json. I have LINT checked the json file and that's free from error, so it's not that. It's something to with the resources. We are using eclipse as our IDE.

junwu
Active Contributor

why this is the answer????

karthikarjun
Active Contributor
0 Kudos

Can you share your code in plunkr.co please?

var oModel1 = new sap.ui.model.json.JSONModel("Testmodel.json"; // Close the bracket




To get model data from view, use this.getView().getModel("MODELNAME") [with the same view-> controller]

outside or other controller-> use this.getView().byId("ID").getModel("ModelName")