我有一个JSON集合
$scope.person = [
{
"Id": 1
"Name": "John"
},
{
"Id": 2
"Name": "Jack"
},
{
"Id": 3
"Name": "Watson"
},
];
在HTML中,我在AngularJS HTML Select中绑定上面的Collection。完整的HTML源代码是
<!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>
&#13;
我在下拉菜单中选择了杰克,我的预期选定值是
{
"Id": 2
"Name": "Jack"
}
但是我以字符串 "{"Id":2,"Name":"Jack"}"
请帮助我,如何将Value作为 JSON对象 ...
答案 0 :(得分:1)
您只需执行以下操作即可获取JSON对象:
JSON.parse(yourJsonString);
所以你的代码应该是这样的:
var newDataJSON = JSON.parse(newData)
var name = newDataJSON.Name