Link the <select> element with ng-options and ng-model, ensuring that the model contains a composite key

I am facing a challenge with my Angular service that retrieves a list of objects with a composite key comprising two parts. I am struggling to write the bindings in a way that properly re-binds existing data. Below is my current attempt:

angular.module("app", [])
  .controller("fooCtrl", function() {
    // Data obtained from Angular service / back-end:
    this.options = [
      { part1: 3, part2: 101, displayName: "Option 3-101" },
      { part1: 4, part2: 651, displayName: "Option 4-651" },
      { part1: 4, part2: 999, displayName: "Option 4-999" }
    ];

    this.item = { selectedOption: { part1: 4, part2: 651 } };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="app" ng-controller="fooCtrl as vm">
  <select ng-options="option.displayName for option in vm.options track by part1 + '-' + part2"
          ng-model="vm.item.selectedOption"></select>
  <hr>
  Debug info:
  <pre>{{vm.item | json}}</pre>
</div>

However, the above setup is not functioning as expected: it should be selecting "Option 4-651" upon loading, but it fails to do so.

Please note that the client-side displayName field is added to the options, but it does not exist in the selectedOption during initialization. I am open to modifying the selectedOption to include the displayName property without affecting the back-end processing since the server-side DTO does not have a displayName property.

Crucially, I am seeking a solution without altering the loading process in the JavaScript or changing the structure of options and selectedOption. Specifically:

  • I understand I could manually reset this.item using logic at the end of the controller method to reference the actual entry in options, though this is complicated in real-time scenarios due to asynchronous loading.
  • I also acknowledge that I could modify both the selectedOption and individual options to incorporate a "composite key" as a "single compound key," like part1and2: "3-101", yet this would require addressing the underlying issue rather than directly binding the UI to DTOs from the back-end.

Is there an elegant way to tackle this using a track by expression in the binding expressions? Alternatively, must I resolve this matter within the controller or service code?

Answer №1

To enhance your JavaScript object binding process, consider restructuring the object to include a new property like part12. This will allow you to easily track and manage the data more efficiently.

Answer №2

If the JSON response includes the displayName, it should also be added to the selectedOption when setting the option in the controller.

Here is an example of how you can achieve this:

angular.module("app", [])
  .controller("fooCtrl", function() {
    // Data from Angular service / back-end:
    this.options = [
      { part1: 3, part2: 101, displayName: "Option 3-101" },
      { part1: 4, part2: 651, displayName: "Option 4-651" },
      { part1: 4, part2: 999, displayName: "Option 4-999" }
    ];

    this.item = { selectedOption: { part1: 4, part2: 651} };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="app" ng-controller="fooCtrl as vm">
  <select ng-options="option as ('Option ' + option.part1 + '-' + option.part2) for option in vm.options track by (option.part1 +'-'+ option.part2)"
          ng-model="vm.item.selectedOption"></select>
  <hr>
  Debug info:
  <pre>{{vm.item | json}}</pre>
</div>

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

What could be the reason for my SQL query functioning correctly in my editor, but not in my JavaScript function?

When I run my SQL statement in my SQL editor, it works perfectly fine. However, when I try to use it in my JavaScript function, I get an error saying there is an invalid column for my client ID. function getFeedposts(data) { var limit = data.dollarLimit; ...

How to use Axios in Vue JS to access an array within a JSON object

Struggling to access arrays inside a JSON object and save them into separate arrays. Despite trying various methods, I have not been successful in retrieving these arrays. I suspect that my approach to accessing arrays within the JSON object is incorrect, ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Is there a way to incorporate text at the end of a row in HTML?

I have a photo and some text on my website. The photo is displayed on the left side, while the text appears nicely on the right side. Now, I am looking to include an additional block of text below the existing text. How can I accomplish this? What steps ...

What is the best method for sending a user to a different page when a webhook is triggered by an external API in

In my project using NextJS and the pages router, I encounter a scenario where a user initiates a process through a form that takes approximately 30 seconds to complete. This process is carried out by an external API over which I have no control. Once the p ...

AngularJS POST request encounters failure: Preflight response contains improperly formatted HTTP status code 404

I have encountered a persistent issue with microframeworks while attempting to perform a simple POST request. Despite trying multiple frameworks, none of them seem to handle the POST request properly: Here is an example using AngularJS on the client side: ...

Is polymer routing the best choice for large-scale websites?

I am currently working on a large project that consists of various layouts and structures, totaling around 100 different pages. Despite the variations in content, the core elements such as headers and menus remain consistent throughout. To streamline my ...

Having trouble simulating getSignedUrl from npm package "@aws-sdk/cloudfront-signer" with jest

I attempted to simulate the npm module "@aws-sdk/cloudfront-signer"'s function getSignedUrl using jest. Below is the code snippet: import { getSignedUrl } from '@aws-sdk/cloudfront-signer' let url = 'test value', // confidential k ...

Running the `npm start` command in Angular tends to be quite time-consuming

When I use Visual Studio Code to run Angular projects, my laptop seems to take a longer time when running the server through npm start compared to others. Could this delay be related to my PC specifications, or is there something I can do to improve it? ...

Update the field 'payments._id' in MongoDB to a timestamp

I need to change the value of 'payments._id' to a timestamp. In MongoDB, the 'payments._id' object is automatically generated when inserting a document into the collection. onMounted(async () => { const res = await axios.get(" ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...

Enhancing website functionality with Regex in Javascript

So, here is the code I am working with: var patt = new RegExp("/.+/g"); var device_id = patt.exec("javascript:project_id:256, device_id:2232"); Surprisingly, after running the above code, the value of device_id is empty and I can't seem to figure ou ...

Determine the outcome of the assessment quiz

Greetings everyone, I apologize for my poor English. I've been searching through numerous documents, but due to my language barrier, I am having trouble understanding them. I have designed a quiz page, but I'm facing an issue where I can't d ...

Preserve information and position from previous state when transitioning to a new state within a modal window, as seen in Instagram and Pinterest routing

I am looking to implement routing similar to Instagram or Pinterest, where the full article opens in a modal window. I came across this code snippet in the FAQ: $stateProvider.state("items.add", { url: "/add", onEnter: ['$stateParams&apos ...

Executing a JS function within a table cell

I've been attempting to invoke a function within a table cell to dynamically create some data, but I keep encountering this error below. I'm uncertain whether I'm correctly calling defined functions and JavaScript functions inside the table ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...

SignalR does not actively send messages to clients

Currently, I'm working on implementing a feature that notifies users when long-running jobs are completed using SignalR in an AngularJS application. To achieve this, I have grouped users based on their names, creating a unique group for each user cont ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

Encountering AngularJS promise data parsing issues

I am trying to work with promises in AngularJS. However, I encountered an error while parsing the backend response in AngularJS. What could be the issue here? This is the HTML code: <div ng-app="clinang" ng-controller="pacientesCtrl"> <a ...

An error known as "cart-confirmation" has been encountered within the Snipcart platform

I am looking to integrate Snipcart checkout in my Next.js application. However, when I try to validate a payment, I encounter an error message: An error occurred in Snipcart: 'product-crawling-failed' --- Item 1 --- [Item ID] 8 [Item Unique ID] ...