user6060080
user6060080

Reputation:

Bind JSON Object as a Value in AngularJS HTML Select - Dropdown

I'm having a JSON collection

$scope.person = [
    {
        "Id": 1
        "Name": "John"
    },
    {
        "Id": 2
        "Name": "Jack"
    },
    {
        "Id": 3
        "Name": "Watson"
    },
];

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"
}

But I'm getting the Value is in the form of String "{"Id":2,"Name":"Jack"}"

enter image description here

Kindly assist me, how to get the Value as a JSON object...

Upvotes: 2

Views: 6525

Answers (1)

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

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

Upvotes: 1

Related Questions