SAPUI5, Access view elements in controller

半城伤御伤魂 提交于 2019-11-28 06:47:42

问题


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?


回答1:


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.




回答2:


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");



回答3:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!