将JSON对象绑定为AngularJS中的值HTML选择 - 下拉列表

时间:2016-07-05 17:07:10

标签: javascript angularjs json html-select

我有一个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;
&#13;
&#13;

我在下拉菜单中选择了杰克,我的预期选定值是

{
    "Id": 2
    "Name": "Jack"
}

但是我以字符串 "{"Id":2,"Name":"Jack"}"

的形式获得了价值

enter image description here

请帮助我,如何将Value作为 JSON对象 ...

1 个答案:

答案 0 :(得分:1)

您只需执行以下操作即可获取JSON对象:

JSON.parse(yourJsonString); 

所以你的代码应该是这样的:

 var newDataJSON = JSON.parse(newData)
 var name = newDataJSON.Name