How to Attach a JSON Object as a Selection in an AngularJS HTML Drop-down Menu

I currently have a JSON collection that looks like this:

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

To display this collection in an AngularJS HTML Select element, I include the following HTML code:

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

When I select Jack from the drop-down list, I expect the selected value to be as follows:

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

However, the actual value I am getting is in the form of a string "{"Id":2,"Name":"Jack"}"

https://i.sstatic.net/mi9Ln.jpg

If anyone could kindly guide me on how to retrieve the value as a JSON object, I would greatly appreciate it...

Answer №1

To retrieve the JSON Object, simply use this method:

var jsonObject = JSON.parse(jsonString);

Your revised code will appear as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vuetify Select with Vuex getters

I am having an issue with my Vuex implementation. I have a getter that retrieves an array which I use in a Vuetify drop down select component. My goal is to insert an additional property at the beginning of the array, but when I try to do so, only a number ...

Validation message does not appear when a radio button is left unchecked

I am facing an issue with my aspx page and CS code. I have implemented two radio buttons, YES and NO, where checking YES makes a textbox visible and checking NO hides it. The problem arises when the textbox is left empty - the validation error is not trigg ...

Trigger JavaScript keypress event on keypress

In my code, I have a function called addMoney() that is triggered by pressing Enter in an input field: $('body').on('keypress', 'input[type=text]', function(e){ if(e.keyCode==13){ var val = $('input[type=te ...

Tips for adjusting the color of multiple classes that have a common class using a toggle feature

I am working on a simple website using bootstrap 4 and SCSS. I want to include a toggler that switches between dark and light modes on the webpage. However, I'm facing an issue with changing the background color of 6 Bootstrap cards, footer, and the t ...

In JavaScript, where are the values saved?

Can you clarify how JavaScript handles storage for primitive types and objects? Are primitive types always stored on the stack and objects on the heap, even within the scope of a function's execution? Also, are globally scoped variables and functions ...

Tips for adding a unique number to a text?

Currently, I am working on a task that involves adding a random number to a string and then interpreting it as a variable name within my innerHTML. var a = Math.floor((Math.random() * 3) + 1); var description1 = "This is description 1"; var description2 ...

I recently upgraded my application to Angular 13, and encountered a "Ivy" related error with the "ngx-popover" library when attempting to run npm start

After updating my app to angular 13, I encountered an error related to the "ngx-popover" library and Ivy when running npm start. In my "package.json": "ngx-popover": "^0.0.16" Current versions being used: Angular CLI: 13.0.4 Node: 16.13.1 Package Manager ...

"Optimizing npm packages for front-end web development in vanilla JavaScript: A guide to bundling for production deployments on

My website is built using vanilla HTML/CSS/JavaScript with ES6 modules and can be deployed to GitHub pages and Netlify. I have set up my site by importing "main.js" in my HTML like this: <script src="js/main.js" type="module" defer&g ...

After the response was sent, an essential member of the C# .net team vanished

When working with a back-end in C# .Net and a client in JavaScript, I am encountering an issue. I make an ajax call to the back-end and receive an object containing members. While debugging on the back-end, I can see the required member when sending the re ...

Creating a static menu icon and implementing a wide dropdown menu in Bootstrap 4

I am facing two major challenges and I am struggling to find solutions for them! Below is the code snippet I am working with: @font-face { font-family: 'yekani'; src: url("../fonts/yekan.ttf"); } @font-face { font-family: 'ye ...

AngularJS - Determine if the component's bindings function is a valid function

I am currently working on verifying if my components are properly bound. Binding a function requires the use of the '&' character. <pipeline-list-item item="item" is-selected="item === $ctrl.selectedItem" on-action=""> < ...

Utilizing Ajax for Dynamically Filling a Dropdown Menu

My journey into the world of Ajax has led me to a state of confusion and frustration. The task at hand is to populate the first box with customer data from the database, then use the customerID to retrieve all vehicleID's using the select.php script. ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

What are the best resources for studying web communication standards like xauth, rest, soap, oauth, and json?

Aspiring to become an Android application developer, I am eager to learn how to integrate web communication into my apps. However, I am unsure of where to begin. Any guidance on how to approach this would be greatly appreciated! PS: I think the term "web ...

An AngularJS project utilizing exclusively EJB

Can an AngularJS application be built directly with EJB without needing to expose them as REST services? Many examples on the internet show that eventually REST services are required to provide data to AngularJS. This means that EJB methods must be expos ...

Issues with Disabling the Browser's Back Button with jquery

I have been attempting to prevent the back button from functioning in a specific Browser, Microsoft Bing. Interestingly, my code works only if I click somewhere in the window first. If I don't click anywhere and try to go back directly, it still allow ...

Modifying the font style within an ePub document can affect the page count displayed in a UIWebView

Currently in the development phase of my epubReader app. Utilizing CSS to customize the font style within UIWebView, however encountering a challenge with the fixed font size causing fluctuations in the number of pages when changing the font style. Seeki ...

The issue of setTimeout malfunctioning when used in conjunction with ajaxStart

I am looking to optimize the appearance of my loading animation during an ajax request by delaying it and ensuring it only shows if the request lasts longer than a second. However, I am facing an issue where even though the delay is set at more than 80 i ...

A guide on replacing certain characters with spaces using AngularJS

I'm struggling with replacing special characters in a name (Inka -Tiitto-s-Camp-Aero-Gravity-Milan-9) with hyphens (-) due to an error message that says, "The URI you submitted has disallowed characters." Additionally, the name appears as (Inka Tiitto ...

The scroll event is triggered only when scrolling upwards

I am encountering an issue with my scroll function. Currently, it only alerts when scrolling to the top instead of the bottom. How can I correct this so that it triggers the alert when reaching the bottom of the page? $(window).scroll(function() { if ...