why can't i use these
sap.ui.getCore().setModel(oModel) and this.getView().setModel("oModel","someModel")
in functions other than life cycle hooks of controller in sapui5.
1. You can access UI5 core using sap.ui.getCore() anywhere from your app as the core is a global object. So, sap.ui.getCore().setModel(oModel) also will work from any part of your code provided the oModel is available in the scope.
2. this.getView() - The reason for this which you feel is available only in the life cycle hooks (onInit,onAfterRendering ...) is this (keyword). You know what, this in the life cycle hooks refers to the controller. In the other functions, this might point to a different value. Say, you have a button and in the press event you wanna set a model. So if you do something like this,
/* view code */
var oButton = new sap.m.Button({press : oController.handlePress});
/* controller */
handlePress : function(oEvent){
console.log(this.getView()); // Error. As this here refers to the control Button & not the controller.
}
You can have a look at this to know, how to make this refer to the controller in the handlePress func()
Is there any way to access controls in controller of my view without giving it an id?
Yes. Let me give you a sample implementation.
/*view code */
createContent : function(){
this.oButton = new sap.m.Button(); // this --> view
}
/* controller */
onInit : function(){
console.log( this.getView().oButton ); // this --> controller. Retrieves the instance of button
}
Regards
Sakthivel