Selecting the default value in an AngularJS dropdown using ng-options

Question 1:

Is there a way to set a default value using ng-option when the data is not in an array format? It seems simple when working with arrays, as I can easily do:

select = $scope.items[0];

You can see a Demo here.

Question 2:

<select ng-model="selected" ng-options="name for (name, value) in items"></select>

I'm confused about how this actually works.^

In my controller, I have a key-value object structured like this:

$scope.items = {
    'one': 30,
    'two': 27,
    'three': 50,
    'four': 15,
    'five': 27,
    'six': 30
};

Answer №1

When dealing with primitive values in an object (like in this scenario), Angular compares them based on their actual value rather than their reference point. So, doing:

$scope.selected = 30;

or:

$scope.selected = $scope.items['one'];

will work without any issues.

However, if the values are non-primitive, I recommend using "track by" to track something other than object equality.

Answer №2

Resolution for

Query 1:

If $scope.items is not an array but rather an object then

select = $scope.items.one; // choose the first one

OR

select = $scope.items['one']; // pick the first one

Query 2:

within your code

 <select ng-model="selected" ng-options="name for (name, value) in items"></select>

and in JavaScript

$scope.secleted = $scope.items['one']

(name, value) in items returns an array of names and values (key-value pairs). You are able to associate the values with their corresponding names. This is why it functions as intended.

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

Tips for Keeping a Responsive Image at the Forefront of a Text-Image Layout as You Scroll

I'm currently in the process of creating a website where text appears on the left side with an accompanying image on the right. The challenge I'm encountering is ensuring that as users scroll, the image adjusts dynamically based on the associated ...

Encountering an issue with WebRTC where the 'addIceCandidate' function on RTCPeerConnection is failing, resulting in an error displayed on the console. However, despite this error

I am facing an issue with connecting two peers using webRTC. While I can successfully display both local and remote videos, as soon as the remote video appears, the candidate object turns null and an error message is logged on the console. TypeError: Fail ...

Tips for incorporating a loading gif image with infinite scroll functionality in an AngularJS application

Imagine a scenario where there is a large amount of data and we decide to implement infinite scrolling with an infinite-scroll-distance of 2. Every time new data is being loaded, an animated loading gif should be displayed. Is such functionality possible ...

EventSource using HTTP Authorization Header for Secure Server Sent Events

Trying to add an Authorization header to an HTML5 EventSource, but struggling due to lack of documentation with Server Sent Events. Currently considering passing authorization data in the URL, although not a preferred method. Utilizing AngularJS and inter ...

Verify if the key-value pair can be found within a multi-layered object

Is it feasible to identify the existence of a key/value pair in any type or level of object, regardless of its structure being unknown beforehand? For instance: Pair to find: "kod": "REVH" Object: { "names": [{ "name1": "xxx", "name2": "yyy", ...

What are the reasons behind the lack of clarity in the cache for an ajax request

I am encountering an issue with my external JavaScript file that is supposed to run the home.php file using an Ajax request. Despite adding a random function to the URL to clear the cache, I am still facing issues with caching in my code. Below is the Ja ...

What is the best way to achieve smooth scrolling on a webpage?

I am looking to create a smooth animated scroll effect on page load to a specific position using jQuery's animate function: $(document).ready(function () { $('html, body').animate({ scrollTop: $('#today').offset().top ...

Updating an array of key/value pairs in Mongoose: A step-by-step guide

Context: I am dealing with an array of objects retrieved from Vue Axios. These objects contain key-value pairs and are stored in the req.body. Request Body: keyValue: [{key:"some key", value:"some value"}, {key:"some key2", value:"some value2"}] Import ...

How to iterate over the request body in Node.js using Express?

When I send a request with data in the form of an array of objects: [ {id: "1"}, {id: "2"}, {id: "3"} ] I am utilizing JSON.stringify() and my req.body ends up looking like this: { '{"id":"1"} ...

What are some techniques for managing scrolling within a particular element?

I am currently working with Vue.js and utilizing Element UI components. I want to incorporate a scroll management function to achieve infinite scrolling. To better understand, please refer to the screenshot in the Example section: Despite trying differen ...

What would cause the Uncaught TypeError: Unable to resolve module specifier "firebase"? Isn't it true that relative references should begin with "/ ", "./ ", or "../ "?

After transitioning my code from v8 to v9 with a modular approach, I encountered an error despite having the rollup package installed. Below is my JavaScript Code: <script type="module"> // Necessary Firebase SDKs // https://fir ...

Unable to establish the origin for an element using JavaScript

Currently, I am developing a simple game in JavaScript that includes a grid and various cells. Here is the current look of the game which functions perfectly. However, I am facing an issue with setting the margin to 0 and wanting to center the canvas inste ...

How do I invoke another function from a factory in AngularJS?

Do I need to move my getTemplates function outside of the return statement? For example, I am not sure what to replace "XXXXXXX" with (I have tried using "this/self/templateFactory", etc.) : .factory('templateFactory', [ '$http', ...

Spinning a point around the center on a canvas

My friend and I are in the process of creating a game, and we've reached the point where we want to implement a radar system. While we have successfully designed a basic radar that displays everything in the correct positions, our next challenge is to ...

I am constantly encountering the error message "Reading 'Linear'' error due to undefined properties in my threejs code

A procedural generation library for threejs caught my attention Here is the link to the library: https://github.com/IceCreamYou/THREE.Terrain Despite following the instructions provided in the ReadMe.md file, I encountered an error that says: Cannot read ...

Halt the execution of JavaScript code

I'm having trouble making this conditional if statement work properly... The line " if ( !$section.id == "no-transition" ) " seems to be incorrect. My goal is to prevent JavaScript from executing on sections with the id "no-transition". Could someo ...

Creating CSS for a specific class on a single webpage can be achieved by targeting that class

Here is my custom style: <style> ul { padding:0 0 0 0; margin:0 0 0 0; } ul li { list-style:none; margin-bottom:25px; } ul li img { cursor: poin ...

Does the unique identifier of the element remain constant in jQuery?

For example: $("#savenew").live('click', function(e) { var user=<?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data:{user: user} , ...

The Everyday Explanation of Same Origin Policy

Could anyone simplify the concept of the Same Origin Policy for me? I've come across various explanations but I'm in search of one that a child can easily understand. I found this link to be quite helpful. Is there anyone who can provide further ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...