Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

sapui5 - Accessing view elements in controller in UI5

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...