Choose the current parent item using Angular's ng-selected and $index

http://plnkr.co/edit/fwwAd4bn6z2vxVN2FUL7?p=preview

On the Plunker page linked above, I am trying to achieve a specific functionality. I would like the 3 dropdown lists to display values A, B, and C initially. When a 4th dropdown option is added, it should include value D as well. The requirement is that all alphabet letters should be selectable from the dropdown list.

<option ng-repeat="n in characters" ng-selected="$index == $parent.$index">{{n}}</option>

When you press ADD, the dropdown selections should show ABC selected initially and remain selected even after adding a new option. However, they are not staying selected. How can I make sure the selections stay selected?

Answer №1

To enhance the functionality of your select element, consider incorporating the ng-options directive.

Here's an example in HTML:

<div ng-app="app">
    <div ng-controller="mainController">
        <div ng-repeat="selected in selecteds track by $index">
            <select ng-model="selecteds[$index]" ng-options="character for character in characters">
            </select>
        </div>
        <button ng-click="addValue()">Add</button>
        <pre ng-bind="characters | json"></pre>
        <pre ng-bind="selecteds | json"></pre>
    </div>
</div>

Additionally, here's the corresponding JavaScript:

angular.module('app', [])
.controller('mainController', function($scope) {
    $scope.characters = ["A", "B", "C"];
    $scope.selecteds = ["A", "B", "C"];
    $scope.addValue = function() { 
        var currGroup = String.fromCharCode(65 + $scope.characters.length);
        $scope.characters.push(currGroup);
    }
});

If you'd like to see this in action, check out this live demo: http://jsfiddle.net/ben1729/djy5ooed/

Answer №2

Enhancing the options with value is essential. Here is a suggestion:

<option ng-repeat="item in choices" value="{{item}}" ng-selected="$index == $parent.$index">{{item}}</option>

Answer №3

I made some adjustments to your configuration in order to dynamically generate the existing options for your character collection and then add the dropdown menus dynamically:

Check out the updated Plnkr here

This process involves the following steps:

 $scope.characters = [];
 $scope.something = [{Name:"Obj1",Selected:"A"}, {Name:"Obj2",Selected:"B"},{Name:"Obj3",Selected:"C"}];

 angular.forEach($scope.something, function(obj, index) {
   $scope.characters.push(obj.Selected);
 });

 $scope.Add = function() {
   var newOption = String.fromCharCode(65 + $scope.characters.length);
   $scope.something.push({Name: "obj" + (parseInt($scope.characters.length) + 1), Selected: newOption});
   $scope.characters.push(newOption);  
 }

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

Creating a dynamic search bar with multiple input fields in HTML

My JSON input for typeahead looks like this: [{"q": "#django", "count": 3}, {"q": "#hashtag", "count": 3}, {"q": "#hashtags", "count": 0}, {"q": "#google", "count": 1}] This is the code I have to implement typeahead functionality: var hashTags = new Blo ...

Ways to update list item text with jQuery

I am attempting to create a button that can replace the content of a list item. Although I have looked at other solutions, I keep encountering this error message: Uncaught TypeError: Object li#element2 has no method 'replaceWith' I have experime ...

The Hidden Power of jQuery: Unleashing the Full Potential of .text()

I'm trying to make two values equal, but it's not working... var rowID = $("#@idSelectObjectGuid").val(); $($(".ls-grid-body tr").children("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="240a64524770454648410a74564d ...

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...

Exploring Error Handling in AngularJS and How to Use $exceptionHandler

When it comes to the documentation of Angular 1 for $exceptionHandler, it states: Any uncaught exception in angular expressions is passed to this service. https://code.angularjs.org/1.3.20/docs/api/ng/service/$exceptionHandler However, I have noticed ...

What causes the maximum update depth exceeded error in React when trying to set data to the context?

When building my React project, I implemented a context to share the selected currency across components. While the context functionality is working well, I encountered a small issue regarding setting a default currency. At the start of the web applicati ...

Displaying selected values in a Multi Select Listbox upon submission of the same form when an error occurs

When the page is first loaded: Retrieve the values from the table field and store them in a variable If the field is blank, do not take any action Populate the listbox with default custom values When the form is submitted (on the same page) and multipl ...

Rendering template and data from a promise in AngularJS: A comprehensive guide

Hey there, I'm diving into the world of Angular and I've been struggling for the past couple of days trying to figure out a solution for this issue. Not entirely sure if my approach is right either. My goal is to create a simple page with a dyna ...

The Angular Google Maps Module fails to initialize

After updating angular-google-maps to version 2.0.1 via bower and adding the required dependencies (bluebird, jquery, loadash), I noticed that my app works fine when I comment out google-maps. This suggests that the issue lies with angular-google-maps. He ...

The React rendering process failed when attempting to utilize a stateless component

Struggling to integrate a stateless component with fetch in my project. The fetch API is successfully retrieving data, but for some reason, the stateless component remains blank. import React, { PropTypes } from 'react'; import { Card, CardTitle ...

Error Occurs When Executing minall Task with Grunt Package (ubuntu and windows)

I've been following a tutorial on installing AngularJS from https://docs.angularjs.org/misc/contribute but I'm facing an issue at this particular step: # Build AngularJS: grunt package Upon executing "sudo grunt package" command, the output ind ...

Exploring the process of breaking down a substantial string object into manageable key/value pairs using AngularJS

I gathered information from a text file called sample_resume.txt Name: John Doe Phone: (555) 555-5555 Email: [email protected] TARGET To succeed in the field of web development. SKILL SET Development: HTML5, JavaScript, Bootstrap, AngularJS, Rea ...

Issue with a input element having relative positioning within a flexbox

Objective: Aim to align the middle DIV (MIDDLE) within a flexbox row in the center. Issue: The right element includes an input element with relative positioning. Consequently, the middle DIV element (MIDDLE) is no longer centered but instead shifted to th ...

Tips for Resolving React.js Issues with setInterval

Is there a way to adjust setInterval in React so that it doesn't count faster than it should at the beginning of my program? Currently, 'var i' is being increased by 2 every second. How can I modify my code to resolve this issue? import Reac ...

Vue 3 feature: Click the button to dynamically insert a new row into the grid

Just starting out in the world of coding, I've zero experience with Vue - it's my introduction to frameworks and arrays are currently my nemesis. In a recent exercise, I managed to display the first five elements of an array in a table after filt ...

Sharing a Detailed Mongoose Schema

Hey there! So, I've been working on this Mongoose Schema and there seems to be something off about it. The main area of concern is the "region" part. const mongoose = require('mongoose'); const destination = new mongoose.Schema({ ...

Rendering a Nativescript component once the page has been fully loaded

I'm currently working on integrating the WikitudeArchitectView into my TypeScript code. I've successfully registered the element in the main.ts TypeScript file: var architectView = require("nativescript-wikitudearchitectview"); registerElement ...

What is the significance of -= and += operators in JavaScript programming language?

I'm puzzled by the mathematical process behind this JavaScript code, which results in -11. let x = 2; let y = 4; console.log(x -= y += 9) ...

Is there a way to showcase the string message from BadRequest(message) utilizing Ajax?

I am currently working on implementing an API Controller. public ActionResult<Campaigns> AddCampaign([Bind("Name, Venue, AssignedTo, StartedOn, CompletedOn")] Campaigns campaigns) { try { if (ModelState.IsVal ...

Disable the enter key from closing the alert box

Is there a way to ensure that a user must manually close a JavaScript alert, preventing them from simply closing it by pressing enter? (It may sound suspicious, but in the application users frequently press enter and I need to make sure they don't ov ...