我正在尝试将JSON data
填充到HTML Dropdown
,我成功地做到了。
现在我想要的是:
单击它时获取所选列表项的ID
(即JSON中的ID而不是DOM ID)所以我这样做了:
$http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
url: 'someURL',
method: 'GET',
})
.then(function(response, status, headers, config) {
var myData1 = JSON.parse(response.data);
// Preparing data to send to DOM
var myNames = [];
$.each(myData1, function(index, value){
// I can use some real data instead of 'Some static string' but just because of ease. I am passing it hard coded.
myNames.push({"name": "Some static string",
"id": 1});
})
/* This is with real data
$.each(myData1, function(index, value){
myNames.push({"name": value.stationNameEn,
"id": value.stationNameid});
})
*/
$scope.names = JSON.stringify(myNames);
console.log(myNames);
})
.catch(function(error, status, headers, config){
console.log("Some problem occured: " + JSON.stringify(error));
})
// Sending data to DOM
$scope.formData = {};
$scope.dropboxitemselected = function (item) {
$scope.formData.selectedItem = item;
console.log($scope.formData.selectedName);
}
在我的DOM上我有:
<select class="ion-input-select padding"
ng-model="formData.selectedName"
ng-options="x for x in names"
ng-change="dropboxitemselected();"
>
</select>
selectedName: {{formData.selectedName}}
问题:
我将所有结果作为对象获取,当我JSON.stringify()
时,它会分成单个字母,如:
r
e
s
u
l
t
s
我想要的是:
当我点击id
时,获取来自JSON
的{{1}}。
答案 0 :(得分:1)
我认为问题是因为
$scope.names = JSON.stringify(myNames);
上面的代码会将myNames对象转换为字符串。当你在ng-repeat中提供一个字符串时,它会迭代每个字符,因此,你得到每个字母。相反,只需使用
$scope.names = myNames;
答案 1 :(得分:1)
您可以更改此类内容以达到您想要的效果:
在控制器中:
更改行:
$scope.names = JSON.stringify(myNames); to $scope.names = myNames
在View / DOM中:
<select class="ion-input-select padding"
ng-model="formData.selectedName"
ng-options="x as x.name for x in names"
ng-change="dropboxitemselected();"
>
</select>
selectedName: {{formData.selectedName.name}}
要在控制器中检索ID:
$scope.dropboxitemselected = function () {
Console.log($scope.formData.selectedName.id);
}