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

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

Ways to access states from a Vuex store within a Vuetify list in VueJs

Here is a snippet from my Vue file: import store from '@/store' export default{ name: 'myList', data: () => ({ show: true, listContent: [{ name: '1', icon: 'pers ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

The UseEffect function ceases to function properly upon refreshing the website

I'm currently using ReactJS for a project. I have a form that is intended to serve as the configuration for another form. The structure of this specific form is as follows: const [startingDate, setStartingDate] = useState(); const [endingDate, set ...

Is the RadioButton change jQuery function malfunctioning following modifications to the DOM?

After updating the HTML of the radio button (with the same name) through AJAX based on certain logic (such as rate or duration changes), I noticed that the change(function(e) method worked perfectly before the DOM was updated. However, once the DOM chang ...

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...

Looking for assistance with creating a D3 bar chart that involves selecting a specific year and crime category? Let me help

I am still learning D3 and I'm facing a challenge while trying to create a bar chart. My idea is to first select the YEAR radio button, then choose the CRIMEHEAD option, and finally the bar chart should be displayed. Here's my thought process: I ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

Is there a way for me to receive the response from the this.$store.dispatch method in vue.js 2?

Here is the structure of my component : <script> export default{ props:['search','category','shop'], ... methods: { getVueItems: function(page) { this.$store.disp ...

What could be causing passport.authenticate to not be triggered?

After multiple attempts to solve my first question, I am still unable to find the answer. Maybe it's due to being a newbie mistake, but I've exhausted all my efforts. This is how I created the new local strategy for Passport: passport.use(new ...

While developing my project in NextJS, I encountered a frustrating issue where the build process would fail consistently, even though the development environment ran smoothly. The

Hello everyone, I'm a beginner posting here for the first time. I am still getting the hang of React and JavaScript in general, and currently working on a project in NextJS. It's interesting to note that my project runs smoothly when I use next d ...

In TypeScript, there is a curious phenomenon where private properties seem to be mimicking the

Here is an example of an issue I encountered while working with private properties in TypeScript. I expected that only the public properties would be visible in my object output, similar to normal encapsulation. My aim here is to include the property wit ...

Change the data-theme using jQuery Mobile once the page has finished loading

I am facing an issue with my buttons in a control group that represent on/off functionality. Every time I click on one of the buttons to switch their themes, the theme reverts back once I move the mouse away from the button. How can I make sure that the ...

Alexa Skills Issue: Problem with Playing AudioPlayer HLS Stream URL

I'm currently using the "AudioPlayer" feature from the "Alexa Skill Kit" to stream an HLS audio format URL. No errors are showing up from AWS Lambda or the Developer Portal. I've been testing it with Silent Echo (). Alexa can play MP3 URLs and so ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

Tips for effortlessly moving content by dragging and dropping it into a text box

Before attempting to create something, I want to verify its feasibility. Begin with a text area that can be pre-filled with text and allow users to add or delete text. Alongside the text area, there are small elements that can be images or HTML components ...

Instructions for utilizing a non-string reference without triggering flow errors

I've noticed that string refs are considered legacy in React. You can read more about it here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md However, I am encountering a flow error in my component and I&apo ...