Implementing dropdown selections with AngularJS's 'ng-options' feature

I am facing a challenge with populating a dropdown menu with prices using AngularJS. The JSON structure provided is complex and I cannot modify it due to its association with a legacy system.

Below is a snippet of the JSON data:

[
    {"name" : "simpleObjectName", "price" : "27.00"},
    {"name" : "simpleObjectName2", "price" : ["26.99", "27.00", "28.00"]},
    {"name" : "complexObjectName1", "availability" : { "price" : ["25.59", "26.40", "27.50"], "availability" : "AVAILABLE"}},
    {"name" : "complexObjectName2", "availability" : { "price" : ["42.99", "22.00", "237.00"], "availability" : "UNAVAILABLE"}},
    {"name" : "complexObjectName3", "availability" : { "price" : ["23.99", "216.00", "21.00"], "availability" : "UNAVAILABLE"}},
    {"name" : "complexObjectName4", "availability" : { "price" : "21.00", "availability" : "AVAILABLE"}}
]

My goal is to display the prices of simple objects in the dropdown, along with the prices of complex objects that are marked as AVAILABLE under availability.

As a newcomer to Angular, I am unsure if there is a solution to handle price visibility within this complex JSON format. Are there any tools or techniques available for achieving this? I initially experimented with filters but encountered errors that forced me to reverse my changes.

EDIT: JSON update reveals the existence of multiple prices linked to offers and color variations. All prices for both available simple and complex objects must be displayed.

Answer №1

To showcase the items within the ng-repeat, use the code snippet below:

<div ng-app="App" ng-controller="MainCtrl">
    <select ng-model="selectedItem" ng-options="c as (c.name + ' - ' + c.price + c.availability.price) for c in containers">
        <option value="">--choose --</option>
    </select>
</div>

Ensure to filter out any unavailable items using this method in your controller:

$scope.containers = [yourcontainerjson].filter(function ($c) {
        if ($c.availability === undefined || 
            $c.availability.availability == 'AVAILABLE') {
            return $c;
        }
 });

You can also create a filter module and incorporate it into the ng-repeat. Try it out on Plunker.

Answer №2

Check out the latest LINK

This is the HTML code:

<div ng-app="App" ng-controller="MainCtrl">
        <h3>Option 1 (standard)</h3>

    <select ng-model="selectedItem" ng-options="c as (c.name + ' - ' + c.price + c.availability.price) for c in containers">
        <option value="">--select --</option>
    </select>

</div>

Answer №3

You have the ability to utilize ng-repeat-start and ng-repeat-end in conjunction with ng-if

Take a look at this demonstration

Code Example

<select>
  <option ng-repeat-start="r in records" ng-if="r.price">{{r.name}}-{{r.price}}</option>
  <option ng-repeat-end ng-if="!r.price && r.availability && r.availability.availability == 'AVAILABLE'">{{r.name}}-{{r.availability.price}}</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

Step-by-step guide on retrieving JSONP data from Angular service within view by utilizing expressions

I have been developing an Angular application that retrieves data from the Strava API. While experimenting with $http.get, I realized that separating the logic into a dedicated service would be more organized, allowing my controller to simply call the serv ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

Having trouble with parsing JSON in Swift 3

{ 1: { cityname_EN: "Munich", cityname_DE: "München", country: "DE", image: "http://res.muenchen-p.de/fl_progressive,q_65/.imaging/stk/responsive/teaser300/dms/sw/bg/muenchen_in_bildern_neu/sehenswuerdigkeiten/top_20_sehenswuerdigkeiten/img/marienplatz/do ...

Convert a JSON list into a 3D format and display it in an HTML template using

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Predictions</title> </head> <body> <div class="results"> <table> {% for item in summary %} ...

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

Issue with jQuery .ajax() not triggering success callback function when using JSONP

My Facebook iframe application is attempting to make a cross-domain request to my server for JSONP data. The client-side code I am using is as follows: jQuery.ajax({ url: '***', type: 'post', ...

Ways to determine when the AngularJS digest cycle is complete without relying on $timeout

I have a query regarding AngularJS. One of the challenges in AngularJS is that it does not provide an event to notify when the digest cycle has finished. To work around this, AngularJS recommends using $timeout to queue your tasks to be executed after the ...

Automating Image Downloads with Puppeteer by Adding Authentication Query String to Image URL

Attempting to save images stored in a web-space account can be challenging. Accessing the private space with credentials and retrieving the image link using Puppeteer works smoothly. However, when the src attribute of the image includes additional authenti ...

In order to display the new component upon the first click in React, my button requires a double click

I have a project that utilizes the open Trivia API to fetch data. I've completed the development and everything appears to be working well so far. However, there's a bug where upon initially rendering the app, the first time I click the button to ...

Is it possible to have a getter in vuex dynamically update when another getter's value changes?

Within my vuex store, I have this getter that retrieves authority_count: authority_count (state, getters) { return getters.dataView?.getUint16(4, true) || state.pack.authority_count; } I want authority_count to default to state.pack.authority_count ...

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

Error: An unidentified type was encountered that is not a functioning element within an anonymous PHP JavaScript function

Hello everyone, I am seeking help with a JavaScript error that is causing some trouble. Whenever I try to sort a table and implement pagination in PHP, I get an error message in the console stating "Uncaught TypeError: undefined is not a function." Despite ...

Display all active services in a new list item using AngularJS Ionic's ng-repeat directive

I've been working on a shopping cart feature for my Ionic app and everything is coming together nicely, except for the running itemized total. By default, the items in my array are set to active:false and when selected, they switch to active:true and ...

Authenticating and authorizing a client-side web application with a Remote NodeJS API integrating Passport.js

Displayed in the diagram below, there is an independent API Project operating on a server with a specific port, for example 3001, and a Web App running on a different server with another port, like 3002. https://i.sstatic.net/ovvAZ.png Running on port 30 ...

Transforming CSV Arrays into JSON using Node.js

Currently, I am extracting information from a URL that contains a csv file. The data format that I am trying to retrieve looks like this: To accomplish this task, I am utilizing Node.js and making use of the nodejs-requestify package: https://www.npmjs.co ...

Updating meta tags dynamically for Facebook sharing using Angular 6

I am struggling to dynamically update meta tags such as og:title, og:description, and og:image for sharing on Facebook. I have attempted various methods without success. Initially, I tried setting meta tags with JavaScript like this: var meta = document. ...

What is the best approach for handling nested conditional statements?

I have a complex set of nested conditional checks that I am working on refining to avoid getting stuck in a nested if{}else{} loop. To provide context, I am dealing with two objects, CACHE_FILE_AGE_LIMIT and CACHE_FILE_CURRENT_AGE, and I am trying to navig ...

What is the process for including an SVG file in my JavaScript .textContent?

I've been struggling to add an exclamation SVG to this section, but for some reason I can't make it work. I've searched on Google for a solution, but haven't found one yet. The SVG file is already downloaded and stored in my project fo ...

Adding turbolinks to an HTML document can be achieved without the need for a

Recently delving into the world of turbolinks, I discovered that it can be employed independently without relying on a client-side javascript framework. Eager to test this out, I created a bootstrap 4 template and attempted to install it. Firstly, I downl ...