Using ng-options in Angular to make four distinct selections: a guide

JS:

angular
.module('app', [])

function MainCtrl() {
    var ctrl = this;

    ctrl.selectionList = [
        { id: 1, name: 'apple'},
        { id: 2, name: 'banana'},
        { id: 3, name: 'grapes'},
        { id: 4, name: 'carrot'}
    ];

    ctrl.selectedThing = ctrl.selectionList[0].name; 

}

angular
.module('app', [])
.controller('MainCtrl', MainCtrl);

HTML:

<div class="row">

    <div class="col-sm-3 col-xs-12 unit">
        <select 
        ng-model="ctrl.selectedThing"
        ng-options="selections.name as selections.name for selections in ctrl.selectionList">
        </select>
    </div>

</div><!--end of first row-->

When implementing this code, it results in creating four different selections. The issue arises when selecting an option like "apple" on one selection, causing all other selections to also display "apple." Is there a way to address this using ng-options or should I resort to coding the select element directly in HTML?

Answer №1

To solve your issue, it is important to utilize ng-options instead of focusing on any other problems. The reason you are encountering difficulties is likely due to having the same ng-model for all select elements linked to the ctrl variable. This means that modifying one dropdown will affect a single variable that pertains to all four dropdowns. In order to address this, you should either create an array for your selected items or have four distinct instances of a selected variable.

ctrl.selectedThings = [ctrl.selectedList[0].name, '', '', ''];

In your view, implement the following approach...

<select 
        ng-model="ctrl.selectedThings[rowIndex]"
        ng-options="selections.name as selections.name for selections in ctrl.selectionList">
        </select>

This solution may not be optimal for scenarios with more than 4 items, but it can be adjusted to accommodate dynamic requirements.

Answer №2

It seems like your code is functioning properly, can you please double-check and confirm?

(function ()
{
    var app = angular.module("app", []);

    function HomeController()
    {
        var vm = this;
        vm.selectionList = [
            { id: 1, name: 'apple'},
            { id: 2, name: 'banana'},
            { id: 3, name: 'grapes'},
            { id: 4, name: 'carrot'}
        ];

    }

    app.controller("HomeController", [HomeController]);

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app="app">
    <head>
        <meta charset="UTF-8">
        <title>Angular JS App</title>        
    </head>
    <body>

        <div class="container" ng-controller="HomeController as homeCtrl">

            <div class="row">

                <div class="col-sm-3 col-xs-12 unit">
                    <select
                            ng-model="homeCtrl.selectedThing"
                            ng-options="selections.name as selections.name for selections in homeCtrl.selectionList">
                    </select>
                    <pre>{{homeCtrl.selectedThing}}</pre>
                </div>

            </div><!--end of first row-->
           
        </div>


    </body>
</html>

Answer №3

When you use ng-model="ctrl.selectedThing" for each <select> tag, they will all synchronize to the same value because they are connected to the same scope property. It's like having multiple variables pointing to the same information: if one is modified, accessing any of them will yield the same outcome.

To address this issue, you should link each select to a distinct property in the scope, such as ctrl.selectedThing1,2,...n. While this approach may not be very scalable, it will resolve the problem at hand.

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

Warning: Neglecting to handle promise rejections is now considered outdated and discouraged

I encountered this issue with my code and I'm unsure how to resolve it. DeprecationWarning: Unhandled promise rejections are deprecated. In the future, unhandled promise rejections will terminate the Node.js process with a non-zero exit code. This ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Struggling with JavaScript code to enable mp3 features

Greetings all! I am a newcomer to this platform seeking assistance with my project. Please bear with me as I am not the most seasoned programmer, so my code may appear a bit messy. Currently, I am working on a music production app using express.js. With ...

Establish a connection to an already existing database using Mongoose

I've been exploring the inner workings of MongoDB lately. After setting up a local database, I created a collection with the following document: db.user.find().pretty() { "_id" : ObjectId("5a05844833a9b3552ce5cfec"), " ...

What are the signs indicating that I've reached the threads limit set in Node.js?

My current configuration includes a thread pool size of 25. process.env.UV_THREADPOOL_SIZE = 25; How can I verify at runtime that all the threads have been used up? Is there a method to detect when all defined threads have been utilized when a new reque ...

Struggling to incorporate pagination with axios in my code

As a newcomer to the world of REACT, I am currently delving into the realm of implementing pagination in my React project using axios. The API that I am utilizing (swapi.dev) boasts a total of 87 characters. Upon submitting a GET request with , only 10 cha ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

Youtube video embedding showing cut edges on smaller screens

Looking for assistance with a Next.js and tailwind site I am building. Having trouble getting the video component to display properly on mobile screens. Tried various fixes but the video still gets cut off on smaller screen sizes. If anyone has a soluti ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

What is the proper way to utilize several initialization functions simultaneously?

I have been pondering the concept of using multiple initialization functions and whether it is considered bad practice. When I refer to an initialization function, I am talking about one of the following scenarios: $(document).ready(function(){ //... ...

Creating a border around a div element using JavaScript

Is there a way to set a border for a div box using JavaScript similar to using border:2px solid #000; in CSS? Can this be done within the following for loop? elements = document.getElementsByClassName("box"); for (var i = 0; i < elements.length; i++) ...

Issue: [AppRoutes] is not recognized as a valid <Route> component

Currently diving into React-Router with guidance from this helpful tutorial: https://blog.logrocket.com/complete-guide-authentication-with-react-router-v6/ Here's a snippet from my App.jsx: import { Route, createBrowserRouter, createRoutesFromE ...

Implementing the Audio() Element with JavaScript

I've written the code below, but it's not working properly! When I click on the play button, nothing happens HTML: <button id="play"><img id="playicon" src="img/Polygon 1.svg"></button> JS: I have a variable named 'song0 ...

Angular JS application failing to load in browser due to a simple issue

I recently completed working on two pages index.html and app.js, which were created while following a helpful tutorial found here. The structure and content of each page are outlined below: index.html <!DOCTYPE html> <html ng-app ="store"> ...

Tips for saving the file path locally using local storage in AngularJS

My attempt at using $localstorage to store the file path locally and preview it using an iframe is resulting in an error. $scope.getResume = function() { var resumeJson = { "json":{ "request":{ ...

Switch back and forth between multiple functions

It appears that the code provided is not functioning correctly with jQuery versions higher than 1.8. Can anyone offer insight on how to achieve the same functionality with newer versions? Additionally, should we be structuring our code like element.click(f ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. https://i.sstatic.net/3GVdYMWl.png ...

Extracting data from a JSON object using Angular

Recently, I've been delving into the world of AngularJS and encountered a hurdle with LocalStorage. After spending numerous hours trying to figure out how to save data locally, I believe I have finally got it working as intended. Now, my next challeng ...

Creating a new array set by utilizing the map method

How can I filter and return a new array using the map function based on 2 conditions: The array must not be empty The role should be "moderator" This is an example of my initial response: https://i.sstatic.net/UeVn3.png Below is a React function that ...

What are the most effective techniques for managing headers, footers, and reusable templates in Node.js/Express views?

Currently, I've got my development environment configured with Node.JS / Express / Pug and I'm in the process of grasping the usage of views & routes. However, I seem to be struggling when it comes to embedding a "reusable" navigation bar and foo ...