Choose the default option from the ng-options

Here is the code snippet and information at hand:

$scope.options = [
  { id: 1, label: "My label" },
  { id: 2, label: "My label 2" }
];
$scope.selected = 2;

<select ng-options="opt.label for opt in options" ng-model="selected">
  <option value="">Select one</option>
</select>

Nevertheless, the rendered options appear as follows:

<select ng-options="opt.label for opt in options" ng-model="selected">
  <option value="">Select one</option>
  <option value="0">My label</option>
  <option value="1">My label 2</option>
</select>

The query now is - how can I designate My label 2 as the selected option? It's achievable by doing this:

$scope.selected = $scope.options[1];

However, my hurdle lies in the fact that these options are generated within a directive. At that instant, I lack knowledge of 1) the number of values in $scope.options, or 2) the index of the chosen option in the database. All that's known is the provided ID (within the object).

The HTML structure of my directive looks somewhat like this:

<select ng-switch-when="select" ng-model="form.model[element.model]" ng-options="{{element.rule}}"></select>

Where element.rule refers to:

rule: "role.role for role in element.options"

And element.options contains an array of available choices, with form.model[element.model] holding the ID of the selected option.

To determine the index of the element with ID X in the array $scope.options, what steps should be taken? The solution appears probable through this approach, but the method remains elusive...

Answer №1

To properly initialize the controller, ensure that you assign the correct model value from the start. Utilize a filter to easily access the desired array element based on its ID:

$scope.selectedItem = $filter('filter')($scope.items, {id: 2})[0];

Answer №2

Your code is encountering an issue where the 'selected' value retrieved from your database is just the ID of the selected object, not the actual object itself. This poses a problem because directly setting $scope.selected = 2 (assuming 2 is the ID from the database) won't work if the value '2' is not present in your option array; only the Object with an ID of 2 exists.

If you are certain that the options in your array follow a sequential order from 1-n, then you can resolve this by updating your code as follows:

$scope.options = [
    { id: 1, label: "My label" },
    { id: 2, label: "My label 2" }
];
var selectedIdFromDatabase = 2;
$scope.selected = $scope.options[selectedIdFromDatabase-1];

However, if you cannot guarantee the sequential order or want to future-proof your code, you will need to iterate through the array to find the object with the corresponding ID from your database.

You can refer to this helpful resource for insights on handling nested objects and arrays in JavaScript.

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

Ways to eliminate the unusual dashed space in ReactJS using Bootstrap

While developing an app with NextJS and Bootstrap, I noticed a strange dashed gap at the top of the screen in the elements tab. Despite checking for margin or padding-top properties on any element, there doesn't seem to be a clear cause for this issue ...

Adjust CRM 2011 settings to allow bulk editing exclusively for specific entities

Currently, my goal is to restrict bulk editing for most entities except for the "Campaign Response" entity. To accomplish this task, I have taken the following steps: Disabled the Out of the Box (OOTB) edit button globally (due to restrictions on editin ...

The latest update to Apache CORS is no longer functioning as expected

After upgrading from Apache 2.2 to 2.4, I had to put in some effort to get PHP and SSL up and running again. However, I am now facing a new challenge that I can't seem to solve - CORS. In my virtual host configuration, I have the following code: Hea ...

Unlocking access: Bearer Authentication for AmCharts JS

I am currently working with a .NET Core server that has an API from which I need to request data using the default loading method in AmCharts. The endpoint on the server side is structured like this: [Authorize] public class StocksController : ApiCont ...

I'm having some trouble with my jQuery.get() function in the javascript Saturday(), can anyone help me figure out what I'm doing wrong?

Can anyone help me troubleshoot my jQuery.get() method in the saturday() JavaScript function? Here is the code snippet I have been working on. This is what I have in my index.html file: <html> <head> <title>jVectorMap demo</title> ...

Sending a function parameter when registering for an event

I am currently utilizing the jQuery pubsub for creating custom events: (function($) { var o = $({}); $.subscribe = function() { o.on.apply(o, arguments); }; $.unsubscribe = function() { o.off.apply(o, arguments); }; $.publish = fun ...

Use JQuery to gradually decrease the opacity of divs individually

I am currently working on a function that fades out all divs except the one that has been clicked on simultaneously. However, I want them to fade out one by one instead. Additionally, I would like the divs to fade out in a random order. If anyone knows ho ...

Twitter-Typeahead is failing to provide any recommendations at the moment

I'm currently implementing twitter-typeahead-rails into my project. The goal is to have suggestions for instances of the "User" model displayed in a drop-down menu as I type in the "#Typeahead" input field. However, when I start typing, nothing seems ...

I am looking to incorporate a dropdown feature using Javascript into the web page of my Django project

According to the data type of the selected column in the first dropdown, the values displayed in the columns of the second dropdown should match those listed in the JavaScript dictionary below, please note: {{col.1}} provides details on the SQL column data ...

Easy steps for entering date and time into a Vuetify text input field

Looking to create a Vuetify form that allows users to input both the date and time of an event for both the start and end times. Currently, my code looks like this: <v-form @submit.prevent="addEvent"> <v-text-field v-mod ...

What is the optimal way to develop an npm module with a predefined name?

I am currently developing a module in nodejs and utilizing NAPI for its creation. Let's assume the name of my module is "hello", so it would be required in JavaScript as require("hello") However, I wish to require it like this require("Name/hello") ...

Ensure that only one menu with a specific class is open at any given time

My goal is to ensure that both menus cannot be open simultaneously. The desired behavior is as follows: When one menu is already open and you click on another, the first one should automatically close. For a better understanding of what I am trying to achi ...

Use jQuery to categorize <a> links by their text content

Hi, I'm new to jQuery and could use some guidance. Due to the not-so-great output of Go's html/template, I have to rely more on JavaScript (which I'm not very good at). I have a list of unordered links that need to be organized into "paren ...

Heroku - Launch your code in development or live environments

I am currently hosting my express API on Heroku with two separate projects set up: one for my Master Branch (Prod) and the other for my Development branch (Dev). Inside my package.json file, I have defined two scripts: "scripts": { "d ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Is there a way to utilize JavaScript and AJAX to save a WordPress cookie and log in a user, all without the need for any plugins?

My goal is to log in to WordPress using only ajax requests. Here's the code I have so far: var username = data.username; var password = data.password; var wp_login_url = "http://local_Ip/api/user/generate_auth_cookie/?username=" +username + "&pas ...

Command for Sniping with Discord.js

I am currently working on creating a snipe command using Discord.js in my bot. I have set up command handlers and everything seems to be working fine, including the on messageDelete event. However, I encounter an error when I delete a user message and try ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

Optimal method for showcasing a large 2-dimensional array

I am considering displaying a 1000x1000 array with elements that are either black or white based on boolean values. I am contemplating using either javascript or winforms for this task, but I want to understand the potential drawbacks of each option befo ...

How to duplicate a single element from a list using the .clone() method in jQuery

My goal is to only add specific items from a list to a new list. For example, I want to add only the "banana" item to my second list. Currently, the code in my function adds all items from coll-selected-list to coll-grouped-list. How can I clone only a par ...