选择元素是一个下拉列表,其中可以选择一个选项。
select元素具有selectedItem,它是当前所选项目的句柄。选定的项目有一个键,我绑定到我的JSON模型中的标识属性。
使用XML视图声明,我可以使用change()事件来触发控制器中的代码。
在change()事件中,如何在不必搜索模型以匹配键的情况下获取selectedItem的绑定路径?
这是我的直觉,但第二行引发了错误。
onListSelect : function(event) {
console.log(event.oSource.getSelectedItem().getKey()) // works ok
var path = event.oSource.getSelectedItem().getBindingContext().getPath(); // Fails
}
编辑:回应输入&评论我添加了片段来隔离问题。在这样做的过程中,我发现没有问题。该片段有效。一定是我自己的错误。
我将很快删除这个问题。
// JSON sample data
var data = {
"peeps": [
{className: "Coding 101", id: 100, firstName: "Alan", lastName: "Turing"},
{className: "Coding 101", id: 400, firstName: "Ada", lastName: "Lovelace"},
{className: "Combat 101", id: 300, firstName: "D", lastName: "Trump"},
{className: "Combat 101", id: 700, firstName: "Spartacus", lastName: ""},
{className: "Combat 101", id: 900, firstName: "Tasmanian", lastName: "Devil"}
]
};
sap.ui.getCore().attachInit(function() {
"use strict";
sap.ui.controller("MyController", {
onInit: function() {
// create JSON model instance
var oModel = new sap.ui.model.json.JSONModel();
// set the data for the model
oModel.setData(data);
// set model to core.
sap.ui.getCore().setModel(oModel);
},
onListSelect : function(event) {
console.log(event.getSource().getSelectedItem().getKey()); // works ok
var path = event.getSource().getSelectedItem().getBindingContext().getPath(); // Fails
console.log("Path=" + path)
var oModel = sap.ui.getCore().getModel()
var theName = oModel.getProperty(path)
console.log("You selected " + theName.lastName)
}
});
sap.ui.xmlview({
viewContent: jQuery("#myView").html()
}).placeAt("content");
});
<!DOCTYPE html>
<title>SAPUI5</title>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m" data-sap-ui-bindingSyntax="complex" data-sap-ui-compatVersion="edge" data-sap-ui-preload="async"></script>
<script id="myView" type="ui5/xmlview">
<mvc:View controllerName="MyController" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:layout="sap.ui.commons.layout" xmlns:f="sap.ui.layout.form">
<Select id="theList" forceSelection="false" wisth="auto" change="onListSelect" items="{
path: '/peeps',
sorter: { path: 'lastName' }
}" class="sapUiResponsiveMargin">
<core:Item key="{id}" text="{lastName}" />
</Select>
</mvc:View>
</script>
<body class="sapUiBody">
<div id="content"></div>
</body>
答案 0 :(得分:2)
检查以下XML和JS代码:
XML代码:
`<Select id="id_Select"
forceSelection="false"
selectedKey="{/Data/0/key}"
change="fnSelectChange"
items="{/Data}" >
<core:Item key="{key}" text="{name}" />
</Select>`
JS代码:
fnInputHandel : function(){
oSelectJSON = new sap.ui.model.json.JSONModel();
var Data = {
Data : [{
name : "name1",
key : "key1"
},{
name : "name2",
key : "key2"
}]
}
oSelectJSON.setData(Data);
this.getView().byId("id_Select").setModel(oSelectJSON);
},
fnSelectChange : function(oEvent){
var value = oEvent.oSource.getSelectedItem().getBindingContext().getPath();
},