Tips for showing the chosen value in a select option field retrieved from a JSON object using AngularJS

After fetching a json object containing the list of countries, I am trying to display the selected country name in a select option box. However, I have encountered issues where only a blank value is shown.

Note: The countries variable holds the json object with key-value pairs representing the countries. This is used to populate the select options in the view. Additionally, tabs[0].data.country refers to the country ID that needs to be pre-selected.

Here are some snippets of code that I have attempted:

Current Output: https://i.sstatic.net/VkHKi.png

Answer №1

To begin, transform your JSON object into an array of objects and then proceed with the following code:

<select name="countries" id="contries" ng-model="vm.country">
  <option ng-repeat="country in vm.countries" value="{{country.id}}">{{country.name}}</option>
</select>

Simply iterate through the array and select the desired elements from the list. For more detailed instructions, please refer to the complete documentation available here: https://docs.angularjs.org/api/ng/directive/select

Answer №2

Finally, after much searching, I found the snippet that resolved my issue.

html

<div ng-controller="ExampleController">
   <form name="myForm">
     <label for="mySelect">Make a choice:</label>
     <select name="mySelect" id="mySelect"
        ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption">
     </select>
   </form>
</div>

js

angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
     selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
     };
 }]);

To find more information, you can visit this link

There's also another helpful tutorial here

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

Transfer the information of a selected element to a different element

Hello, I am trying to transfer content from a child element to another element. In my HTML setup, there is a hidden div named "DetailsExpanded" and multiple items called "IconWrapper". When an "IconWrapper" is clicked, I want to copy the content of its "I ...

What causes the discrepancy in time between a node.js server and mongodb?

I have a document in my mongoDB database with an attribute 'dia' that is a Date set to: 'ISODate("2018-09-07T20:00:00.000Z")' An issue arises when attempting to retrieve this document in my node.js server. I am currently using mongo ...

Creating a custom inner class in JAVA to handle complex JSON data involves defining a class within

I have gone through many posts but I can't seem to find a solution on how to create a class for this JSON. { "snippet": { "parentGroupId": "69ea5920-0157-1000-0000-0000028e1b90", "processors": {}, "processGroups": { ...

I'm having trouble getting jQuery to work properly with Bootstrap buttons

In simple terms, my objective is to have two buttons on a page where "1" is displayed when the first button is pressed and "2" is displayed when the second button is pressed. This functionality works fine with radio inputs, but when I incorporate button la ...

Package for validating forms in Meteor using React

Looking for recommendations on a Meteor React form validation package or custom validation code that's compatible with components. Need something similar to jQuery validate, but specifically designed to work seamlessly with Meteor and React. ...

successful callback after passport registration

router.post('/register', function(req, res, next){ var name = req.body.name; var email = req.body.email; var username = req.body.username; var password = req.body.password; var password2 ...

what version of Node.js is required for Ionic V1.4.3

I prefer using Ionic V1.X for its compatibility with AngularJS that supports .js, compared to Angular with .ts support. However, when I attempt to check my Ionic version using "ionic -v," the output shows: ReferenceError: primordials is not defined at Mo ...

Closing a live search box by tapping away from it

The link I found as the best example for this topic is: http://www.example.com In the example provided, if you enter a keyword in the search field, suggestions will drop down. I have implemented this code but would like to make a slight modification. I w ...

Generate permutations with a specified length parameter using a JavaScript permutation generator

Many generators I've come across create a squared matrix, assuming the output length based on the number of items provided. However, I'm looking for a solution where I can specify both the items and the desired length. It seems like such a simpl ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Results from AWS DynamoDB Scan operation

I am currently utilizing the AWS JavaScript SDK for DynamoDB, and executing a scan operation to retrieve a list of items from a table. The returned results show that each value is enclosed within an attribute type key: For instance: An anticipated result ...

Pull information from nested JSON arrays and organize it into a more streamlined array

I have a JSON payload formatted with nested arrays that I need to simplify into a single array. Here is an example of the input: [ { "pim_network": [ { "addresses": [ { "ifindex": 1, "ifname": "lo", ...

How can I convert a .json file into a mongoose schema?

I am currently working with a .json file that contains dictionaries (objects) and arrays. Previously, the front-end would request this .json file directly from the server. However, I have now integrated a mongo database into the system. I believe it would ...

Using knex.js to pipe data to an express server

I'm encountering an issue with knex.js and express. Here is the code snippet in question: userRouter.get('/:userId', function (req, res) { DB('users').where({ id: req.params.userId }).first('name').pipe(res); }); ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

Ways to retrieve a value from a multidimensional array in PHP

Hey there! I'm currently in the process of building a website using PHP that utilizes a JSON API. My goal is to echo the values of a multidimensional array from my JSON file. "troopsLevels": [ { "value": 5, "globalID": 4000000 }, { "value": 5, ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

What could be causing the page to refresh every time a post or update is made using a mock REST API with JSON

I have been using Json-Server to mock API requests, but I'm facing an issue where the page reloads every time I fetch or update a post. I've tried searching for a solution, but haven't found one yet. Interestingly, even though I followed a ...

Is there a chance of overlooking messages when utilizing long polling with nginx and the pushstream module?

After extensive research through documentation, forums, and examples, I have not been able to locate a clear description of how the pushstream module functions in the following scenario: I am utilizing nginx+pushstream to provide status updates for users ...

Is this approach to implementing content security policy acceptable?

I am in the process of implementing CSP on my web application. I have included the following meta tag in my index page: <meta http-equiv="Content-Security-Policy" content="img-src 'self' data:;default-src *;style-src 'self' http://* ...