Using AngularJS to create a select dropdown menu with nested objects as the options

Currently, I am working on developing an AngularJS application with a complex data structure.

The data source consists of an array of individuals with their languages and skill levels. My goal is to be able to filter these individuals based on language skill. I attempted to create a select dropdown for the languages and another one for the skill levels, but unfortunately, I was unsuccessful in my attempts.

Click here to see my efforts on Plnkr

I am wondering if there might be a simpler or more effective way to structure the data array ($scope.people)

Answer №1

Check out this code snippet

Live Demo Here

HTML Code:

<div ng-app='myApp' ng-controller="MainCtrl">LANGUAGES:
    <select ng-model="selectLang" ng-options="lang as lang for lang in languages"></select>
    <br>SKILL:
    <select ng-model="selectSkill" ng-options="skill as skill for skill in skills"></select>
    <br>
    <button ng-click="getPeople()">Submit</button>
    <br>PEOPLE:
    <select ng-model="selectPeoples" ng-options="people as people for people in peoples"></select>
</div>

Javascript:

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

    $scope.people = [{
        "name": "Jane Doe",
            "gender": "Female",
            "languages": [{
            "lang": "German",
                "skill": "Good"
        }, {
            "lang": "English",
                "skill": "Very Good"
        }]
    }, {
        "name": "John Doe",
            "gender": "Male",
            "languages": [{
            "lang": "French",
                "skill": "Good"
        }, {
            "lang": "English",
                "skill": "Very Good"
        }]
    }];

    $scope.languages = [];
    $scope.skills = [];
    angular.forEach($scope.people, function (peopleValue, peopleKey) {
        angular.forEach(peopleValue.languages, function (langValue, langKey) {
            $scope.languages.push(langValue.lang);
            $scope.skills.push(langValue.skill);
        });
    });

    $scope.languages = _.uniq($scope.languages);
    $scope.skills = _.uniq($scope.skills);



    $scope.getPeople = function () {
        $scope.peoples = [];
        angular.forEach($scope.people, function (peopleValue, peopleKey) {
            angular.forEach(peopleValue.languages, function (langValue, langKey) {
                if (langValue.lang === $scope.selectLang && langValue.skill === $scope.selectSkill) {
                    $scope.peoples.push(peopleValue.name);
                }
            });
        });
    }
});

Answer №2

The issue at hand is that you are not properly iterating through each person's list of languages within your ng-options directive. It seems unlikely that this can be achieved given the structure of your data. It doesn't appear that nested arrays can be looped through with ng-options or that there is a syntax to support such an operation.

To simplify things, I recommend the following approach in your controller:

$scope.langs = [];
angular.forEach($scope.people, function(person){
    angular.forEach(person.languages, function(lang){
        $scope.langs.push({
            lang: lang.lang,
            skill: lang.skill,
            name: person.name,
            gender: person.gender
        });
    });
});

By implementing this solution, you will create an array that enables you to utilize ng-options with the 'orderBy' filter effectively.

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

Leverage data retrieved from a JSON response to dynamically populate variables on a webpage through an AJAX API

After making an AJAX call to my API and receiving JSON data, I am looking to dynamically update my webpage using specific values from the JSON response. <div class="Name"></div> <div class="Role"></div> <div class="Location"> ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

Is it feasible to develop an asynchronous function in Node.js that executes concurrently?

My objective is to simultaneously execute the longRunnigTask and quickTask functions: function longRunnigTask() { return new Promise((resolve) => { console.log('longRunnigTask started'); for (let i = 0; i < 999999999; i+ ...

When integrating matter-js and applying a Body using fromVertices, the alignment of the resulting vertices may be inaccurate in relation to one another

Take a look at the shape I'm anticipating. The vertices along the edge outline the points. https://i.sstatic.net/YpQrR.png This is the json file (derived from the image above) that I'm importing and using to construct the Body. { "cann ...

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

What could be causing my Amazon slot to return an undefined value?

Currently, I am working through this tutorial: https://medium.com/@itsHabib/integrate-an-amazon-lex-chatbot-into-a-react-native-app-1536883ccbed Upon running my chatbot, the JSON output is as shown below: { "dialogState": "Fulfilled", "intentName": ...

The function url_for is failing to interpret the variables I am passing to

My goal is to allow users to upload images that are then displayed to all users. The variable "Data" holds the file name (e.g., "files/dog.png"). However, when I try to set the newImg.src value as "{{url_for('static', filename = data )}}", it onl ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

Interacting with a non-stringified object displayed in the browser console using TestCafe

Upon receiving a page that logs an object to the console, I encountered an issue when trying to access this object using getBrowserConsoleMessages(). The object appeared as the String "[object Object]" in the console, making it impossible for me to parse ...

Positioning a div above a Bootstrap navbar that disappears when scrolling

I am currently using bootstrap to design a website, and I am attempting to create a div that would initially appear above the navbar on an unscrolled webpage. However, once the user starts scrolling, I want this div to disappear and have the navbar fill it ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

Increase the date and time by a specified number of days

After searching for solutions on how to add a specific number of days to a given date, I came across various methods. However, my requirement is to add days to both Date and Time in the format MM-DD-YYYY HH:MM:SS. I attempted a method which worked fine wh ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

When utilizing jade.compile for compiling a jade template containing mixins or included partials

I'm currently exploring solutions for this challenge. The issue at hand involves compiling a jade template for an email campaign, but the file I am attempting to compile is a mixin that includes some partials. Here's an example: controllers/us ...

The power of Ng-show and filtering

What I am aiming for is to display a complete list of cities as soon as the page is loaded. Once a user clicks on a checkbox next to a city, my goal is to utilize ng-show/ng-hide in order to display the results specific to that city while hiding those of ...

When I start scrolling down, the Jumptron background image vanishes

Utilizing bootstrap jumptron with a background image has led to an issue where the background image disappears as I scroll down, leaving only the jumptron div class displaying the heading. How can this be fixed so that the image remains visible even when s ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

Using checkboxes in an Express application

Currently, I am working on the task of parsing checkbox values into an array using express/ejs. Users are required to fill out a form and select checkboxes as shown below: Answer: Checkbox: The goal is to create two arrays from the input data: answer = ...