"Displaying array objects in a select dropdown menu - a step-by-step guide

I need assistance with displaying an array object in a select tag utilizing only AngularJS. Below is the structure of my array object:

"matcherObject": {
"Percentage Off": [
  {
    "dealType": "Percentage Off",
    "subCategory": "16% to 20%",
    "recid": 2
  },
  {
    "dealType": "Percentage Off",
    "subCategory": "10 to 15 %",
    "recid": 1
  },
  {
    "dealType": "Percentage Off",
    "subCategory": "21% to 25%",
    "recid": 3
  }
],
"Special Deals based on the event": [
  {
    "dealType": "Special Deals based on the event",
    "subCategory": "Buy 1 get one entr",
    "recid": 52
  },
  {
    "dealType": "Special Deals based on the event",
    "subCategory": "Buy 1 get one entr",
    "recid": 54
  }
]
};

I am seeking guidance on how to display this object in a select tag. Below is an illustration of how it should appear in the user interface:

Upon selecting a tag, the ng-model should be displayed in the following format:

{"dealType": "Percentage Off","subCategory": "16% to 20%","recid": 2}

Answer №1

To select an object, you should utilize ng-options. Refer to the Angular documentation for more information on ng-options.

var app = angular.module("App", []);
app.controller("Ctrl", function($scope){
$scope.reqObj =     {"matcherObject": {
"Percentage Off": [
  {
    "dealType": "Percentage Off",
    "subCategory": "16% to 20%",
    "recid": 2
  },
  {
    "dealType": "Percentage Off",
    "subCategory": "10 to 15 %",
    "recid": 1
  },
  {
    "dealType": "Percentage Off",
    "subCategory": "21% to 25%",
    "recid": 3
  }
],
"Special Deals based on the event": [
  {
    "dealType": "Special Deals based on the event",
    "subCategory": "Buy 1 get one entr",
    "recid": 52
  },
  {
    "dealType": "Special Deals based on the event",
    "subCategory": "Buy 1 get one entr",
    "recid": 54
  }
]
}
};


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" data-ng-controller="Ctrl">
<select data-ng-model = "selOption" data-ng-options="perc as perc.subCategory for perc in reqObj.matcherObject['Percentage Off']">
</select>

<hr />


{{ selOption | json }}
</div>

Answer №2

When dealing with nested lists, it is necessary to use ng-repeat twice and also assign the deal-type-name to a name property for display purposes.

I have made some adjustments:

$scope.matcherObject = [{
    "listName": "Discounts",
    "items": [{
      "dealType": "Percentage Off",
      "subCategory": "16% to 20%",
      "recid": 2
    }, {
      "dealType": "Percentage Off",
      "subCategory": "10 to 15 %",
      "recid": 1
    }, {
      "dealType": "Percentage Off",
      "subCategory": "21% to 25%",
      "recid": 3
    }],
  }, {
    "listName": "Event-based Deals",
    "items": [{
      "dealType": "Special Deals based on the event",
      "subCategory": "Buy 1 get one entr",
      "recid": 52
    }, {
      "dealType": "Special Deals based on the event",
      "subCategory": "Buy 1 get one entr",
      "recid": 54
    }]
  }]

HTML Output

<ul ng-repeat="listItem in matcherObject" >
  {{listItem.listName}}
    <li ng-repeat="item in listItem.items">
        {{item.subCategory}}
    </li>
</ul>

For a working example, you can visit: Plnkr

EDIT1:

The code snippet below will achieve the desired result without altering the script:

<ul ng-repeat="listItem in matcherObject">
    <li ng-repeat="item in listItem">
      <ul>
        <li ng-repeat="subItem in item">
          {{subItem.subCategory}}
        </li>
      </ul>
    </li>
</ul>

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

Do the benefits outweigh the challenges of integrating AngularJS and KendoUI together?

Working with AngularJS has been a great experience for me recently, especially in creating custom abstract data factories. The features it offers are really impressive. KendoUI also provides similar features like MVVM and SPA routes that AngularJS offers. ...

Vue.js having compatibility issues with Semantic UI dropdown feature

I have recently started exploring Vue.js and I must say, I really enjoy using Semantic UI for my projects. In Semantic UI, dropdowns need to be initialized using the dropdown() function in semantic.js. This function generates a visually appealing HTML str ...

"Encountered a malfunction in the dialogue system on the second attempt

Looking for a way to pass an array to a Modal Dialog using a template. My approach, based mostly on AngularJS documentation, is working initially but has issues with subsequent openings of the dialog: angular.module("materialExample").controller("calenda ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

React navigator appears stuck and unable to navigate between screens

I encounter an issue where my app closes when I press the switch screen button, but there is no error output displayed. I have checked for any version discrepancies and found no problem. The function I implemented for the button is functioning as expected ...

What is the best way to connect information from an HTML input field to a JavaScript object with the help of AngularJS?

As a beginner in AngularJS, I'm struggling to find the best approach to achieve my goal. I aim to create a grid of input tags with type=number in my HTML and have it set up so that whenever the value is increased, a new object is added to a list. Simi ...

Set the style of the mat-select element

I'm having an issue with my select option in Angular Material. The options look fine, but when I select one, the strong tag disappears. Can anyone help me style only that part? Thank you in advance. <mat-select formControlName="projectId" ...

Dreamweaver constantly combines an external CSS file with locally stored CSS when running on a local server

When I used Dreamweaver CS5, XAMPP Server, and PHP files in the past, I encountered an issue. The websites within my htdocs folder seemed to be pulling a specific website's CSS file. In 'Live View,' I could see all external .css and .js file ...

Can LocalStorage be deleted when the application is not running?

Can a specific key in an application's LocalStorage be deleted without having to open the app? I'm considering creating a batch file script for removing a particular key from the app's LocalStorage while the app is not running. The challeng ...

Substitute "Basic Authentication" with "Form Authentication"

Is there a way in W20 to switch from using "Basic Authentication" to "Form Authentication"? The current documentation mentions only the use of "basicAuth" and does not provide information on implementing form authentication. Our app is built with Angular ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

The list item click event is not triggered when new list items are added

I've run into a bit of confusion with my code. Everything seems to be working perfectly fine until I introduce new items. Take a look at a sample of my items However, once I make changes to my list, the click function stops working. Check out a sa ...

Resolving duplicated controller code in Angular using UI.Router

During the process of updating my app to utilize UI.Router's state.resolve in order to streamline some controller logic, I encountered a common issue: How can one prevent code duplication that occurs when fetching dependencies in resolved assets and u ...

Is there a way to determine the model name programmatically within a Sails.js lifecycle callback?

Two models are present, with one model extending from the other. For all sub-models to inherit a lifecycle callback defined in BaseObject, I need a way to retrieve the name of the model being acted upon within the callback. This information is crucial for ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

When comparing strings, if they match, replace them with bold text

Today, I faced a challenging brain teaser that kept me occupied for over an hour. The task at hand is to compare two strings: the text input from the field and data-row-internalnumber. The goal is to determine if they match and then bold only the last let ...

Learn the process of updating a nested document within an array in MongoDB

I have a data structure as shown below: { "name":"xxxxxx", "list":[ { "listname":"XXXXX1", "card":[ { "title":"xxxxxx", "descip":"xxxxxxx ...

The onChange method seems to be malfunctioning when used with radio buttons

I'm having an issue with my form's radio button. It is supposed to do something when the selected item changes, but it only works when the page first loads and not when I select a different item. Below is the code snippet: <div key={item} cla ...

What is the best method to access the query string or URL within an AJAX page?

I recently discovered how to extract query string parameters from this helpful resource. However, I am facing difficulty retrieving the URL within the requested page via ajax. For instance: <div class="result"></div> <script> $(func ...