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

Exploring the attributes of cycled values in Vue.js

Currently, I am iterating over a list as shown below: <li v-for="item in filteredParentItems" v-if="item.action === 'list'" v-on:click="getNextPath" v-bind:data-next-path="item.nextPath" v-bind:data-action="item.action ...

What steps can be taken to verify if the user has transmitted a JSON Web Token?

Recently started using Express and been struggling with this particular error for quite a while. const token=req.header("jwt") console.log(token) if(!token ){ return res.json('no jwt') console.log('nojw ...

What is the reason behind ASP MVC model binder's preference for JSON in POST requests?

Is there a way to bind data to a model when sending a 'GET' request with JSON.stringify() using AJAX? Currently, the model value is always null when using 'GET', but it works fine with 'POST'. Are there any solutions for this ...

Highlighting menu elements when landing on a page and making another menu element bold upon clicking in WordPress

I've been searching extensively for a solution to this issue. I'm trying to make the menu item DE appear bold when entering the site, and if I click on EN, I want DE to return to normal (thin) font while EN becomes bold. You can find the site he ...

User authentication on AngularJs is only initiated on the second interaction

My personally built AngularJs user authentication system is experiencing an unusual issue. While everything seems to be working fine - I can login, check access for specific pages, etc. - there is a strange behavior with the token authentication. It seems ...

Printing the elements of an array in a repetitive sequence

var arr = [a, b, c]; In this specific array setup, index 0 corresponds to "a", index 1 corresponds to "b", index 2 corresponds to "c". console.log(arr[0]) // will output > "a" console.log(arr[1]) // will output > "b" console.log(arr[2]) // will ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

Dynamic TextField sizing

I am currently facing an issue while displaying data on a webpage using TextField component from @material-ui. Each record of data has varying lengths, making most values appear unattractive (occupying only 10% of the textfield width). Even though I am ut ...

Having trouble with IE7 - unable to interact with elements below popup form

<script type="text/javascript">var switchTo5x=true;</script> <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script> <script type="text/javascript">stLight.options({publisher:'b42661f5-2dc5 ...

What is the method for swapping out the <button> element with the enter key?

I have a webpage where users can post status updates, and other users can comment on these statuses by typing in the textbox and clicking the 'Reply' button. However, I would prefer to remove the button so users can simply press the enter key to ...

Instead of using an ID in javaScript, opt for $(this) instead

Is there a way to utilize $(this) instead of an ID in the option select function in javaScript? var tot = 5 * ($( "#firstOne option:selected" ).text()); In the scenario mentioned above, I aim to substitute $(this) for #firstOne, allowing this functional ...

Is there a way to retrieve all "a" tags with an "href" attribute that contains the term "youtube"?

My goal is to capture all a tags that have the href attribute containing the word youtube. This task requires the use of jquery. ...

Click on the link or tab to update the marker location on the Google Map

Can you click on Tab 2 to change the marker/location, and then go back to Tab 1 to switch it back to the original location? [Links to Fiddle] http://jsfiddle.net/ye3x8/ function initialize() { var styles = [{ stylers: [{ saturati ...

Capturing an image of an HTML5 canvas that includes an image object: tips and tricks

After creating a canvas and adding various objects like images, clipart, and text to it, I encountered an issue. When capturing a snapshot of the canvas with only text using the method `canvas.toDataURL()`, the snap is correct. However, when I include an i ...

The Blueimp File Uploader seems to be sending numerous submissions at once

I've been tasked with fixing an issue on our site that I didn't originally build. The previous developer who worked on this project is now occupied with another task, leaving me to figure out what's going wrong. We are utilizing the basic bl ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Invoke the onload event from document.ready using jQuery

Is it possible to trigger the onload event from within jQuery's document.ready function, such as in the example below: $(function() { onloadfunc(param); }); Comparison: <body onload = "onloadfunc(param);"> Do the above two methods achieve th ...

One way to add a JSON object to an empty JSON array using Javascript involves pushing

Currently, I am facing an issue with an empty JSON array. shoppingCart: [] In addition to the empty array, I also have a JSON object defined as follows: let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"}; M ...

tips for exporting database information to an excel file with the help of ajax request and javascript

Recently, I built an application using NDWS with sapui5 _javascript. Within the application, there is a table that contains data synced with the server's database. My goal is to retrieve this data from the table and export it to an Excel document. Her ...

AngularJS - Hiding Elements Dynamically Using `ng-hide` Based on an

Is it possible to create an inline expression for ng-hide in the following manner: ng-hide="userType!=user" Please advise on how to achieve this. ...