Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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...

share|improve this question
    
1) Json object, not json document. 2) One solution is just using JSON.parse(yourJsonString) – juvian Jul 5 '16 at 17:09
up vote 1 down vote accepted

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
share|improve this answer
    
Thanks a lot... – user6060080 Jul 5 '16 at 17:13
    
@IRPunch If this helped can you please accept the answer? – Pritam Banerjee Jul 5 '16 at 17:13
    
@IRPunch Thanks a lot – Pritam Banerjee Jul 5 '16 at 17:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.