Using Ng-options in AngularJS to populate a select dropdown with an array of arrays

I'm encountering an issue with displaying options from an array of arrays in a select dropdown. Can someone point out what I might be doing wrong? Check out my code here: https://plnkr.co/edit/HMYbTNzkqkbAGP7PLWWB?p=preview

Here's the HTML snippet:

<div ng-controller="MainCtrl">
   <table>
     <tr ng-repeat="r in rows track by $index">
         <td> 
            <select ng-model="r.name" 
                   ng-options="option.name as option.name for option 
                                           in availableOptions">
                <option value="">Select Value</option>
            </select>
         </td>
          <td> 
              <select ng-model="r.value"
       ng-options="opt.name for opt in option.value for option  in availableOptions | filter:{name: r.name}">
       <option value="">Select Value</option>
        </select>
         </td>
         <td> 
             <input type="button" ng-click="addRow()" value="Add">
         </td>
         <td>
             <input type="button" ng-click="deleteRow($index)" 
                 value="Delete">
        </td>
    </tr>
  </table>

  <div>
    {{rows}}
  </div>

And here's the relevant JavaScript section:

 var bb = [];
  ... (content omitted for brevity, see original text)

  $scope.availableOptions = [
                { name: 'TestA',
                  value : aa
                },
                { name: 'TestB',
                  value : bb
                },
                { name: 'TestC',
                  value : cc
                },
                { name: 'TestD',
                  value : dd
                },
                { name: 'TestE',
                  value : []
                }
            ];

My question is, how can I specify the ng-options for the "value" which is an array filtered based on name: 'TestE' or something similar?

Answer №1

There are a couple of issues in your code:

1# The variables aa, bb, cc, dd have not been assigned any values and remain empty.

2# When using the filter function, it will return an array, so you should access the first element like this:

<select ng-model="r.value" 
       ng-options="option.name as option.name for option 
                               in (availableOptions | filter:{name: r.name})[0].value">
    <option value="">Select Value</option>
</select>

You can view an updated version here: https://plnkr.co/edit/cQTISC1SPucCCRQQ8ca7?p=preview

Answer №3

To populate the child dropdown, first store the child collection in an array and then use that array:

        <select ng-model="selectedChildren" 
               ng-options="option.value as option.name for option 
                                       in availableOptions"
                data-ng-change="childOptions = selectedChildren">
            <option value="">Select Value</option>
        </select>

        <select ng-model="value" 
               ng-options="option as option.name for option 
                                       in childOptions track by $index">
            <option value="">Select Value</option>
        </select>

In this code snippet, after selecting an option from the parent dropdown, the value property (representing the child dropdown collection) is stored in a variable called childOptions. This childOptions variable is then used to populate the child dropdown.

https://plnkr.co/edit/mXz8jpzTrnRoqx5r7b1W?p=preview

Answer №4

Kindly implement the suggested modifications and proceed with testing,

var app = angular.module('plunker', []);
app.filter('ddOptions')
app.controller('MainCtrl', function($scope) {

  $scope.rows = [{name:""}];
  $scope.secondOptions = [];

  $scope.addRow = function(){
    $scope.rows.push({name:""});
  }

  var bb = [];
  bb.push({name:"CCCC"});
  bb.push({name:"AAAA"});
  bb.push({name:"DDDD"});  

   var aa = [];
  aa.push({name:"CCCC"});
  aa.push({name:"AAAA"});
  aa.push({name:"BBBB"}); 

   var cc = [];
  cc.push({name:"BBBB"});
  cc.push({name:"AAAA"});
  cc.push({name:"DDDD"});


   var dd = [];
  dd.push({name:"CCCC"});
  dd.push({name:"AAAA"});
  dd.push({name:"CCCC"});

  $scope.availableOptions = [
                { name: 'TestA',
                  value : aa
                },
                { name: 'TestB',
                value : bb
                },
                { name: 'TestC',
                value : cc

                },
                { name: 'TestD',
                  value : dd

                },
                { name: 'TestE',
                  value : []
                }

            ];

  $scope.populateOptions = function(name){
    var temp = $scope.availableOptions.filter(function(val){ return val.name === name;  })
    console.log(temp);
    $scope.secondOptions = temp[0].value;
  }
  $scope.deleteRow = function(index){
    $scope.rows.splice(index,1);
    }
});

Additionally in the HTML section,

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7868980928b8695c98d94a7d6c9d3c99f">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
       <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  </head>

<body>
<div ng-controller="MainCtrl">
   <table>
     <tr ng-repeat="r in rows track by $index">
         <td> 
            <select ng-model="r.name" ng-change="populateOptions(r.name)" 
                   ng-options="option.name as option.name for option 
                                           in availableOptions">
                <option value="">Select Value</option>
            </select>
         </td>
          <td> 
            <select ng-model="r.value" 
                   ng-options="option.name as option.name for option 
                                           in secondOptions">
                <option value="">Select Value</option>
            </select>
         </td>
         <td> 
             <input type="button" ng-click="addRow()" value="Add">
         </td>
         <td>
             <input type="button" ng-click="deleteRow($index)" 
                 value="Delete">
        </td>
    </tr>
  </table>

  <div>
    {{rows}}
  </div>
</div>
  </body>

</html>

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

Ensuring the successful execution of all AJAX calls (not just completion)

I've seen this question asked many times about how to trigger a function once all AJAX calls have finished. The typical solution involves using jquery.stop(). However, my situation is unique - I want to display a confirmation banner only after all AJA ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Exploring the powerful trio of Node.js, MySQL, and asynchronous iterative functions

Currently grappling with an iterative function in nodejs. I'm traversing through an object and checking for any attached sub-objects (imagine a star having a planet with a moon that has an orbital station with a ship). The aim is to construct an arr ...

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...

Adjust the size of an image within a canvas while maintaining its resolution

My current project involves using a canvas to resize images client-side before uploading to the server. maxWidth = 500; maxHeight = 500; //handle resizing if (image.width >= image.height) { var ratio = 1 / (image.width / maxWidth); } else { var ...

Is it necessary to insert a thread sleep in HtmlUnit before clicking a button?

I have been experimenting with HtmlUnit to extract scores from the BBC Sports website Upon loading the page, it initially displays Premier League scores. To view scores for other leagues, one must use a dropdown menu and click the 'Update' butto ...

What could be causing this test to fail when testing my API endpoint?

Why am I encountering this error? Uncaught exception: Error: listen EADDRINUSE: address already in use :::3000 import supertest from "supertest" import axios from "axios" import app from ".." const request = supertest(app ...

Delivering seamless css integration using express.js

Lately, I've been struggling with serving CSS using Express.js. After some trial and error, I managed to make it work. However, I'm puzzled as to why my new code works while the old one doesn't. Here's the code that now works for me: co ...

Is Dealing with Multiple AJAX Requests a Pain?

Currently, I am utilizing AJAX to retrieve a list of active streams from TwitchTV along with their viewers, updating every second. Sometimes the stream list can become quite long, so my plan is to divide the AJAX requests into 2 or 3 parts: 1) Obtain Numb ...

Is there a way to verify the custom form when the braintree PayPal checkout button is clicked?

I am seeking a solution to validate a custom PHP form when the Braintree PayPal checkout button is clicked. Currently, the form redirects to the PayPal screen if it is not properly filled out. My goal is to prevent the PayPal popup window from opening if ...

What is the best way to loop through ng-repeat with key-value pairs in order to display each

I need to loop through and show the data stored in "detailsController". <div ng-controller="detailsController"> <div ng-repeat="data in details" id="{{data.Id}}"> {{data.Name}} </div> </div> ...

Is there a way to automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

Creating point illustrations with Three.js

Looking to incorporate random points into a web project using Three.js. Here's the current code: <script type="module"> import * as THREE from 'https://threejs.org/build/three.module.js'; import { TrackballControls ...

Is there a way to export the HTML table content to an Excel sheet that is compatible with browsers such as Internet Explorer, Mozilla Firefox, and others?

Welcome to my HTML Page! <html> <head> <title>Table </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> </script> </head> <body> <table ...

What is the order of execution for AngularJS directives?

When using an AngularJS custom directive that executes a function, followed by a regular directive like ng-repeat, which one takes precedence in execution? For instance, if I have a select element with a custom multi-select directive and an ng-repeat dire ...

I have successfully implemented the Context API in my Next.js project and everything is functioning smoothly. However, I encountered an error while using TypeScript

Currently, I am working on a Next.js project that involves using the Context API. The data fetched from the Context API works perfectly fine, but I am encountering errors with TypeScript and I'm not sure how to resolve them. Error: Property openDialo ...

Adjust the color of the button and update the text using AngularJS

i have been attempting repeatedly, but to no avail. Here is my button: <div ng-class="User.active? 'btn btn-danger' : 'btn btn-success' " ng-click="User.active=!User.active"> {{ User.active ? 'Desactive' : &apo ...

Instructions for updating the Modal Value using ajax

This is the script I use to retrieve the data <script> $(document).ready(function() { $('.tmpsurat').click(function() { var id=$(this).data('id'); var url ='{{URL('/cekSuratKelengkapan')}}/'+id; ...

Ways to determine the total amount of days in a given month

As I create a countdown timer, the process involves determining the remaining days in a given month by subtracting the current date from the total number of days in that month. For instance, if there are 30 days in September and 8 days have already passe ...

Refreshing data in AngularJs is like pressing the reset button for

My database contains a list of customers who joined in different years. I have configured my API accordingly and it works smoothly. The issue I am facing is that when using AngularJS to pull the data with the same route (/customers/:id), it doesn't re ...