将JSON对象绑定为AngularJS HTML Select中的值-下拉列表 [英] Bind JSON Object as a Value in AngularJS HTML Select - Dropdown
本文介绍了将JSON对象绑定为AngularJS HTML Select中的值-下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在收集JSON
$scope.person = [
{
"Id": 1
"Name": "John"
},
{
"Id": 2
"Name": "Jack"
},
{
"Id": 3
"Name": "Watson"
},
];
在HTML中,我将以上Collection绑定到AngularJS HTML Select中.完整的HTML源代码为
In the HTML, I bind the above Collection in AngularJS HTML Select. The Complete HTML Source Code is
<!DOCTYPE html>
<html>
<head>
<title>HTML Select using AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="md-block">
<label>Person</label>
<select ng-model="selected.person">
<option ng-repeat="key in person | orderBy:Id" value="{{key}}">({{key.Name}})</option>
</select>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.person = [
{
"Id": 1,
"Name": "John"
},
{
"Id": 2,
"Name": "Jack"
},
{
"Id": 3,
"Name": "Watson"
}
];
$scope.selected = {
person: null
};
$scope.$watchCollection('selected.person', function (newData, oldDaata) {
var obj = JSON.parse(newData);
if ((obj != undefined) && (obj != null) && (obj.Id != undefined) && (obj.Id != null) && (obj.Id != "0")) {
var name = obj.Name;
alert(name);
}
});
});
</script>
</body>
</html>
我在下拉菜单中选择了杰克,我的预期选择值为
I Selected Jack in the Drop Down, My Expected Selected Value is
{
"Id": 2
"Name": "Jack"
}
但是我得到的值是字符串 "{"Id":2,"Name":"Jack"}"
But I'm getting the Value is in the form of String "{"Id":2,"Name":"Jack"}"
请协助我,如何获取作为 JSON对象 ...
Kindly assist me, how to get the Value as a JSON object...
推荐答案
您只需执行以下操作即可获取JSON对象:
You can just do the following to get the JSON Object:
JSON.parse(yourJsonString);
因此您的代码应如下所示:
So your code should look like:
var newDataJSON = JSON.parse(newData)
var name = newDataJSON.Name
这篇关于将JSON对象绑定为AngularJS HTML Select中的值-下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文