When my button is pressed, I want to get in my controller, access my button and change the text to new text for example.
The onClick event works fine. But I stuck at accessing the view element (myButton) from the controller.
I know there are threads about this topic, but I couldn't apply any of them.
sap.ui.getCore().byId() for example didn't work for some reason.
Does anyone got some hints or detailed information about accessing view elements from the controller?
The IDs of the elements of a view shall be created with the View.createId(sId). createId(sId) prefixes the given sId with the ID of the view to create a global ID. With that your sId does only have to be unique inside your view. So you can use something like "button1" without any side effects. createId("button1") will return something like __xmlview1--button1. If you are using XMLViews the id attributes will automatically be converted to global IDs (View.createId() is internally called by the xml parser).
The pendant to View.createId(sId) is View.byId(sId). It looks up the the element with the given view-locale ID sId. As a shortcut the Controller brings its own byId(sId) function that delegates to the views byId() function.
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="view1">
<Button id="button1" press="onButton1Press" text="show my ID"/>
<Label id="label1" />
</mvc:View>
onButton1Press:function(oEvent){
var button = oEvent.getSource();
var label1 = this.byId("label1");
label1.setText(button.getId()); //Label displays "__xmlview0--button1"
}
Example on jsbin.
If you have - for some reason - a global ID then you have to use sap.ui.getCore().byId(sId) to look up the element.
If you use no views at all or JSViews without createId(), then your IDs will be global.
For the event "press", named for example "onPressMyButton" of the button, you can use:
onPressMyButton: function(oEvent) {
var idOfMyButton = oEvent.getSource().getId();
var myButton = this.getView().byId(idOfMyButton);
myButton.setText("New Text");
}
Or in any part of the controller inside of any function, you can use:
var myButton = this.getView().byId("idOfMyButton");
myButton.setText("New Text");
inside view :
var oButton = new sap.ui.commons.Button("this.createId("myButton")",{
text:'Click Me',
press: function(){
controller: functionName(optional);
}
});
inside Controller try to do like this:
sap.ui.getCore().byId(this.createId("myButton")).getValue();
hope this will help you.
来源:https://stackoverflow.com/questions/36134942/sapui5-access-view-elements-in-controller