angular: setting default selected items in dynamically generated options

After looking at the example provided here, I noticed that all three select options have the same value. How can I ensure that each option has a different selected value?

This is what I currently have:

<li ng-repeat="tarea in tareas">
      <input type="checkbox" ng-model="tarea.COMPLETADA" ng-change="updTarea(tarea.ID)"/>
      <span class="done-{{tarea.COMPLETADA}}" >{{tarea.NAME}} {{tarea.CLASIFICADORES}}</span>
      <select ng-model="selectedOpt" 
      ng-options="clasificador.NAME for clasificador in clasificadores">
      </select>
      <button class="buttons delete right" ng-click="delTarea(tarea.ID)"> Eliminar</button>
    </li>

I want to have 5, 10, or 15 options and make sure that each displays a different selected value based on tarea.CLASIFICADORES. I tried setting it with:

$scope.selectedOpt = $scope.clasificadores[1]

But this sets all the options to the same value, as shown in the example. How can I dynamically set different selected values for each option based on the data from my ng-repeat loop?

The data is loaded via ajax...

My main issue is setting the default selected item based on tarea.CLASIFICADORES. For instance, if I have a to-do list with classifiers, I want the ng-options to automatically select the classifier value from my database when the page loads.

Answer №1

One issue you may encounter is using the same scope variable for all selections. A possible solution is to store the selected options in an array as shown below:

function TestCtrl($scope) {
  $scope.items = [
    { id: 1, class: 1 },
    { id: 2, class: 2 },
    { id: 3, class: 1 },
  ];
  $scope.classes = [
    { name: "class 1", id: 1},
    { name: "class 2", id: 2},
    { name: "class 3", id: 3}
    ];
  };
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <div ng-controller="TestCtrl">
    <div ng-repeat="currentItem in items">
      <select ng-model="selectedClass[$index]" ng-init="selectedClass[$index]=(classes|filter:{id: currentItem.class})[0]" ng-options="class.name for class in classes track by class.id" >
      </select>
      selected class: {{selectedClass[$index]}}
    </div>
  </div>
</div>

In this instance, I utilize the $index variable provided by the ng-repeat directive. This allows accessing the current index of the repeat-loop.

UPDATE

The code snippet has been updated to set the default value for each select input.

Each item now includes a field with the corresponding class ID. The select input initialization is done using ng-init, setting selectedClass[$index] as the current item's selected value. As only the class ID is available in the item properties, a filter is used to find the matching class object based on the ID

(classes|filter:{id: currentItem.class})[0]

To avoid relying on the filter, assigning the full class object to each item instead of just the ID can be considered.

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

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

Include a photo in the notification when utilizing the sendToTopic function

I am looking to utilize the sendToTopic method for sending notifications to a topic. Is there a way to include an image in the notification? It seems that notification.imageUrl is not available as an option. ...

Masonry layout organizes images in a vertical stack, with one image per row

After implementing Masonry on my website, I encountered an issue where all the images stack vertically in a single row once the page loads. Instead, I would like them to stack both horizontally and vertically. You can view the problem on My Jsfiddle. This ...

How to successfully transfer input data from a dialog to a controller using jQuery and Grails

As a newcomer to Grails and jQuery, I recently created a jQuery dialog following this example: http://jqueryui.com/dialog/#modal-form The goal is to open a dialog, input data, and have it displayed in a dynamic table on the main page. Once all entries are ...

Retrieve a unified data array from the provided data source

Below is a snapshot of my data const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw ...

Stop jQuery Tab from Initiating Transition Effect on Current Tab

Currently, I am utilizing jQuery tabs that have a slide effect whenever you click on them. My query is: How can one prevent the slide effect from occurring on the active tab if it is clicked again? Below is the snippet of my jQUery code: $(document).read ...

Troubleshooting: AngularJS filter is not functioning properly in combination with jQuery

I have a collection of items stored in the variable $scope. I have connected these items to jQuery events and added an input field for filtering. Everything is functioning properly. However, when I enter text into the input field, the filtered out items r ...

The `<Outlet/>` from react-router is being rendered in a location outside of its intended wrapper div

Utilizing MUI for crafting a straightforward dashboard featuring an <AppBar>, a side <Drawer>, my component appears as follows: <> <AppBar> // code omitted <AppBar/> <Drawer> // code omitted <Drawer/> / ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Tips for patiently waiting for a function that is filled with promises

Consider the following function: const getData = () => { foo() .then(result => { return result; }) .catch(error => { return error; }); }; Even though getData does not directly return a promise, it internally handles asynchro ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...

Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this: <?php $iTime = time(); while(time()-$iTime < 10 ) { echo "Hello world"; echo str_repeat( ' &apos ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Python.Selenium. Unable to locate current element. Techniques for switching frames

I am trying to collect feedback from a specific page at this URL. After waiting for the page to load, I attempted to locate elements using Google Chrome inspector. However, Selenium is unable to find these elements, and I also could not find them in the p ...

Firebase Firestore is returning the dreaded [object Object] rather than the expected plain object

I've created a custom hook called useDocument.js that retrieves data from a firestore collection using a specific ID. However, I'm encountering an issue where it returns [object Object] instead of a plain object. When I attempt to access the nam ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

Enhance your browsing experience by inputting valuable information into the

I am looking to enhance a text box by adding values. The text box already has a default value of 10, and I want to create a button that will add new text boxes with a limit of 4. My goal is to continuously add values from text box 1 to text box 4. For exa ...