Using AngularJS to populate dropdown options with data from JSON objects

I have a JSON file that looks like this:

var myJson = {
   "Number of Devices":2,
   "Block Devices":{
      "bdev0":{
         "Backend_Device_Path":"/dev/ram1",
         "Capacity":"16777216",
         "Bytes_Written":9848,
         "timestamp":"4365093970",
         "IO_Operations":87204,
         "Guest_Device_Name":"vdb",
         "Bytes_Read":107619,
         "Guest_IP_Address":"192.168.26.88"
      },
      "bdev1":{
         "Backend_Device_Path":"/dev/ram2",
         "Capacity":"16777216",
         "Bytes_Written":10062,
         "timestamp":"9365093970",
         "IO_Operations":93789,
         "Guest_Device_Name":"vdb",
         "Bytes_Read":116524,
         "Guest_IP_Address":"192.168.26.100"
      }
   }
}

I am trying to populate a dropdown menu with the names of block devices (bdev0 and bdev1) from the JSON file. However, when I tried the following code snippet, it only returns [Object object] in the dropdown:

View:

<select ng-model="selectedDevice" ng-options="item as devices['Block Devices'] for item in selectdevice">
    <option value="">Select Device</option>
   </select>

Controller:

.controller('timeSeriesCtrl', function($scope, $timeout, $http) {

    $scope.selectedDevice = null;
    $scope.selectdevice = [];
    $scope.bytesRead = [];
    $scope.bytesWritten = [];
    $scope.IoOps = [];
    $scope.currentTime = [];
    var path = 'http://orbit5.ds.cs.umu.se:8888/vrio/debug/blk'


function getData(){
  $http.get(path)
  .success(function(data){
    $scope.devices = data
    angular.forEach($scope.devices['Block Devices'], function(value, key){

           $scope.selectdevice = key;
})


  })
}

getData();





});

Answer №1

Instead of using the forEach method, try utilizing the (key,value) syntax within the ng-options directive.

function fetchData(){
  $http.get(url)
  .success(function(data){
    $scope.devices = data
    //angular.forEach($scope.devices['Block Devices'], function(value, key){
       //$scope.selectedDevice = key;
    //   value.key = key;
    //})
  });

In your HTML template:

<select ng-model="selectedDevice" 
      ng-options="item as key for (key,item) in devices['Block Devices']">
    <option value="">Select a Device</option>
</select>

Check out the example on: https://jsfiddle.net/ncapito/4mqFJ/6/

Answer №2

When you use object.toString(), it returns [object object].
Object.prototype.toString()

To display keys, you can utilize the syntax (key, content).

<select ng-model="selectedItem">
      <option ng-repeat="(key, content) in myjson['Block Devices']" value="{{item}}">{{key}}</option>
</select>

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

Guide on transforming an array containing indexed objects into a simple object

Can anyone help me with converting an array of this specific type? place: [ { "_id": "xxxxx", "loc": [ 0: "xxx", 1: "xxx" ] } ] Into something ...

Implementing ajax functionality to dynamically insert various user inputs upon a button click

I'm searching for resources or materials that explain how to use jQuery and AJAX to create a feature where multiple inputs can be added to a form with just one click. Google's Gmail client is a perfect example of this functionality, as it enables ...

Is there a way to change the domain for all relative URLs on an HTML page to a different one that is not its current domain, including in HTML elements and JavaScript HTTP Requests?

I am dealing with a situation where my page contains "domain relative URLs" like ../file/foo or /file/foo within a href attributes, img src attributes, video, audio, web components, js ajax calls, etc. The issue arises when these URLs need to be relative ...

Creating a webpage that dynamically loads both content and video using HTML and Javascript

I designed a loading page for my website, but I could use some assistance. The loading page remains visible until the entire HTML content is loaded and then it fades out. However, I am facing an issue because I have a background video that I want to load ...

Nuxt: Delaying Loading of Google Maps in VueJS Until Data is Fully Prepared

Hello, I am currently working on my very first VueJS project and I have successfully implemented the vue2-google-maps. However, I have encountered a problem while trying to connect the map markers to my site's JSON feed through the Wordpress REST API. ...

What is the best way to link optional and undefined paths in AngularJS routing?

When it comes to AngularJS routing, I have a question. How can we combine the use of a star (*) to match paths with slashes and a question mark (?) to match optional paths? Specifically, I am looking to match both /admin/tasks and /admin/tasks/arbitrary/pa ...

Optimizing the rendering of Font-awesome CDN JS for better performance on Pagespeed Insights

Instead of directly linking to the Font Awesome CSS, I have chosen to leverage the JavaScript provided by the trustworthy and efficient Font Awesome CDN. This allows for asynchronous loading of icons on my homepage, ensuring a seamless user experience. How ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Creating a function that assigns an anonymous function which in turn returns another anonymous function

Can you explain the difference in JavaScript between these two code snippets? var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { loadData(e.target.result); }; })(file); reader.readAsText(file); a ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

Utilize Grunt to retrieve a JSON object from a file

I'm interested in utilizing the grunt-hash plugin to rename my JavaScript files. This plugin generates a new file that contains a map of renamed files: hash: { options: { mapping: 'examples/assets.json', //mapping file so your s ...

AngularJS: Ensuring Controller Functions are Executed Post AJAX Call Completion via Service

Here's the code snippet I have in my service. this.loginUser = function(checkUser) { Parse.User.logIn(checkUser.username, checkUser.password, { success: function(user) { $rootScope.$apply(function (){ $rootScop ...

Hidden overflow and identification in URL causes content to be invisible and suddenly appear at the top of the page

I'm encountering a strange issue with containers that have overflow:hidden and when the page URL includes an id. The content gets pushed up and becomes invisible. This problem arises when I apply padding and negative margin at the bottom to create equ ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

Utilize an array value as a parameter for getStaticProps within Next.js

Currently, I am fetching my Youtube playlist using a fetch request and utilizing getStaticProps(). However, I am encountering an issue where my playlist is dependent on the result of an array of objects. export async function getStaticProps(){ const MY_P ...

The @JsonIgnore annotation is failing to function as expected

It seems like the @JsonIgnore annotation is not functioning as expected in my project. I have come across some suggestions stating that this issue may arise due to the use of incompatible Jackson versions (org.codehaus vs. com.fasterxml). However, I am onl ...

Display the number of rows per page on the pagination system

Looking for a way to add a show per page dropdown button to my existing pagination code from Mui. Here's the snippet: <Pagination style={{ marginLeft: "auto", marginTop: 20, display: "inline-b ...

The service's wrapping of the http.get() call resulted in an undefined return

I've run into an issue where the http request is successful in fetching data from the server, but for some reason, $scope.catalogue always ends up being undefined. It seems this could be happening because the assignment occurs before the response is r ...

Failed Ajax request is caused by an incorrect URL

In my current project using Ajax, I encountered a peculiar issue. The main page, Main.html, is accessible locally at 'http://localhost/Main.html', and it is styled with Bootstrap. Upon loading the page, jQuery verifies the existence of a particu ...

'AngularJS' filtering feature

I am dealing with an array of objects and I need to extract a specific value when a key is passed in the 'filter' function. Despite my best efforts, the controller code snippet provided below returns an undefined response. Can someone please assi ...