Show a property from the local storage as an option in ng-options

Within my Angular application, I keep crucial victim data in local storage. This data is then showcased in the view where it can be altered (via a <select>):

<h1>Victim #{{victim.numero}}</h1>

<label>Victim status</label>
<select ng-model="victim.status" ng-options="s.libelle for s in status"></select>

<label>Victim situation</label>
<select ng-model="victim.situation" ng-options="s for s in situations"></select>

An issue arises when attempting to display the value stored in victim.status by default upon refreshing the page (the value is not null). Interestingly, this problem does not occur with victim.numero or victim.situation.


Using the provided Fiddle, here's a scenario that illustrates the bug:

  1. Open the Fiddle
  2. The status input will be empty, despite having a defined variable bound
  3. Make a change, click "Save changes": the input displays correctly
  4. Press F5: The variable updates correctly in local storage, but remains invisible in the input
  5. Note that the situation input continues to function properly

The key distinction between victim.status and victim.situation lies in the fact that status is an object while situation is a string.


I've created a simplified code snippet to replicate the issue:

JSFiddle demonstration


My aim is to have the status input automatically populated with victim.status upon page load, how can I address this?

Appreciate any guidance!

Answer №1

There seems to be an issue with your ng-options directive. Since your select list is composed of objects, you should consider adding the track by clause.

<select ng-model="victim.status" ng-options="s.libelle for s in status track by s.libelle"></select>

View the working code on JSFiddle

The reason why using track by is necessary in this case is because the array inside your select contains objects. This results in the generated HTML looking like this:

<select ng-model="victim.status" ng-options="s.libelle for s in status" class="ng-pristine ng-valid ng-touched">
    <option value="?" selected="selected"></option>
    <option label="Unknown" value="object:3">Unknown</option>
    <option label="Safe" value="object:4">Safe</option>
    <option label="Dead" value="object:5">Dead</option>
</select>

https://i.sstatic.net/Uq9xy.png

As shown above, the value of victim.status does not match object:4.

By using track by, the value in the attribute gets replaced and only the specified property of the model is used instead of the entire model. The resulting HTML will appear like this:

<select ng-model="victim.status" ng-options="s.libelle for s in status track by s.libelle" class="ng-pristine ng-valid ng-touched">
    <option label="Unknown" value="Unknown" selected="selected">Unknown</option>
    <option label="Safe" value="Safe">Safe</option>
    <option label="Dead" value="Dead">Dead</option>
</select>

Therefore, instead of checking if victim.status === "Safe", it will compare victim.status.libelle == "safe" after implementing track by.

I hope this explanation clarifies the issue for you. Feel free to reach out if you need further clarification.

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 to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

I keep encountering a 'Missing Permissions' issue whenever I attempt to execute the ban command in Discord.js. What could be causing this problem?

While working on coding a ban command for my Discord server, I encountered an issue where the command was not working as expected. Upon testing, I received an error message on the console stating DiscordAPIError[50013]: Missing Permissions. This was puzzli ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Toggle the checkbox to either select or deselect the value

I am attempting to toggle the value of a checkbox. When checked, the value should be set to active, and when unchecked, it should be set to disabled. The current code successfully changes text based on the checkbox status, but the issue is that the value ...

I am experiencing issues with datejs not functioning properly on Chrome browser

I encountered an issue while trying to use datejs in Chrome as it doesn't seem to work properly. Is there a workaround for this problem if I still want to utilize this library? If not, can anyone recommend an excellent alternative date library that ...

Display a bootstrap toast using a JavaScript class method

One way to display a bootstrap toast is by using the following code snippet: let my_toast = new myToast('title', 'hello world'); my_toast.show(); Currently, I am loading the HTML content from an external file named myToast.html: < ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

What is the best way to update the text on buttons once they've been clicked for a variety of buttons

I'm encountering an issue with multiple buttons where clicking on any button causes the text to change on the first button, rather than the one I actually clicked on. All buttons have the same id, and using different ids for each button seems impracti ...

Executing Javascript to populate a div element with content based on its CSS class

Is there a way to isolate my View (HTML & CSS files) within a controller like JavascriptCode/AJAX, so that upon page load, only the controller binds the data to a specific element such as a DIV based on its class? Do you think this is achievable? If so, ...

Tips for setting up Code Coverage in a Cypress environment for testing a NextJS build simultaneously

We are currently exploring the possibility of integrating code coverage into our setup utilizing cypress and nextjs. Within our cypress configuration, we utilize the next() function to mimic backend requests within nextjs. The cypress.config.ts file is st ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

Having trouble creating a report with an HTML screenshot using Protractor

Need assistance with generating reports using a html screenshot in Protractor. I have followed all the necessary steps but encountered an error. Any help would be appreciated. Here is my conf.js: // Sample configuration file. var HtmlReporter = require(& ...

Manipulating binary data through the use of encodeURIComponent

Currently, I am reading a binary file by making a jQuery ajax get request. The file (a zip file in this instance) is returned as a string. After performing some actions on the file within the browser without modifying it, I need to send it back to a server ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...

iOS Simulator offers a range of both offline and online events for testing purposes

I have been working on a phonegap 3.3 application that incorporates angularjs. When testing the application in my browser, I am successfully able to detect and respond to 'offline' and 'online' events. However, when I switch to the ios ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...