Setting the startup value does not automatically select the value

Check out this angular.js example I created to demonstrate my issue: example

I am trying to set the initial value of a select element to a specific value.

    <select name="i" id="i" ng-model="selectedItem">
        <option ng-repeat="i in items" value="{{i}}">{{i}}</option>
    </select>

The options and the select element are being displayed correctly. However, even when I set the value to 6 in my controller, the selected value on the page remains the first element.

scope.selectedItem = 6;

There are two simple buttons that can change the selected value with no issues.

UPDATE: I have updated the jsfiddle by removing unnecessary code and providing clearer names for better understanding.

UPDATE 2: Can someone help me figure out how to fix the second select element as well? This time, the array contains objects instead of numbers.

    <select name="o" id="o" ng-model="selectedItem">
        <option ng-repeat="o in objects" ng-value="{{o.ID}}">{{o.Text}}</option>
    </select>

Answer №1

Avoid using ngRepeat to display option elements in a select menu as it may not function correctly. Instead, utilize ngOptions which is designed to work smoothly with ngModel:

<select name="i" id="i" 
        ng-model="selectedItem"
        ng-options="i for i in items">
</select>

When working with a second select box where the ngModel is linked to the ID property of objects within an array, your code should resemble:

<select name="o" id="o" 
        ng-model="selectedItem" 
        ng-options="obj.ID as obj.Text for obj in objects">
</select>

See a live demonstration here: http://jsfiddle.net/d3jf7ueq/9/

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

Clear the cache in Angular to remove the page

Within my current project, I am utilizing angular's $routeProvider to dynamically load pages into an ng-view section. The loaded pages are displaying correctly in the ng-view and are being cached for quick access without needing to make a new server r ...

Utilize the child array to retrieve the total number in the table

Dealing with JSON data, my task is to count the number of strings within a specific child element and then group them by part of the string to create a table. While this may seem like a confusing and daunting challenge, it's what we need to accomplish ...

TypeScript - patiently anticipating the completion of nested for loops

Currently, I am working on a task that involves implementing two nested for loops in my code. The primary objective of the first loop is to make an API call, which is dependent on the IDs selected by the user. Unfortunately, the limitation of passing only ...

Simply double-clicking in the 2D sheets view on the left panel will display PDF files in the Autodesk viewer

After discussing the information in this forum post, I have successfully displayed the 2D sheets view (left panel) in the Autodesk viewer for PDF files and other 2D files. https://i.sstatic.net/OFATj.png https://i.sstatic.net/WXMlT.png However, I am fac ...

Set a timeout for a single asynchronous request

Is there a way to implement a setTimeout for only one asynchronous call? I need to set a timeout before calling the GetData function from the dataservice, but it should be specific to only one asynchronous call. Any suggestions? Thank you. #html code < ...

Creating a flash message following a redirect in AngularJS

Just diving into Angular JS and need some clarification. How can I set a flash message after a redirect? Here's my scenario: I have a form where I save data using an HTTP request. Upon success, I navigate to another page using window.location(). Now, ...

I designed a dropdown menu with a searchable <mat-select> feature, where selecting an item is automatic when a space bar is pressed in the search box

Description : I have implemented a dropdown list using element that contains a list of items along with a search field. This allows users to easily search for specific items in the list instead of manually scrolling through a long dropdown menu. They can ...

What could be causing the image to not show up in Angular?

I created a table in my demo with the assistance of this provided example. Within this example, the first column contains an image labeled as "edit image" (taken from bootstrap). When I attempted to replicate the same example in my plunker, which already ...

Verification of version numbers

When it comes to my product version number, it follows the format "P.Q.R", where P, Q, and R are represented by digits. The acceptable inputs include "P", "P.Q", and "P.Q.R". I created a regular expression that involves an OR operation. (^\d+$) | (^ ...

Implementing JavaScript to provide personalized error messages for empty form fields

I am facing an issue with form validation on iPhone / Safari, as they do not recognize the required attribute. I want to display individual error messages below each empty input field using JavaScript. Although my code is functional, the problem is that t ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/ ...

Save the content of a string object into an array

I am currently implementing an array sorting functionality using the MVC approach. The array called "array" is used to store values provided at runtime. Within the view, there is a textbox and a button for user input of integer values. Upon clicking the bu ...

There seems to be an issue with the accurate calculation of the screen width while utilizing the scrollbar-gutter

Please take note: The scrollbar-gutter: stable; property is not compatible with Safari. Additionally, the issue seems to be specific to Chrome and works fine in Firefox. I have observed some unusual behavior when attempting to position elements fixed to t ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

The element does not recognize the property 'width' since it is not defined in the type of 'GlobalEventHandlers'

I'm trying to determine the size of an image using JavaScript, but I encountered a TypeScript error: const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ ...

Issues arise in TypeScript when attempting to assign custom properties to a Vue component

I was working on implementing Vue middleware and faced an issue while trying to add a custom property to one of my components in Vue. Here's the code snippet: middleware.js: import { VueConstructor } from 'vue/types'; function eventPlugin(v ...

What is the preferred method for logging out: using window.location.replace('/') or setting window.location.href to window.location.origin?

When it comes to a logout button, which is the better option: window.location.replace('/') or window.location.href=window.location.origin? Can you explain the difference between these two methods? It's my understanding that both of them remo ...

The Vue.js integration fails to function within Laravel 5.5's environment

When the + sign is clicked, I want to add a new text field to an existing form. This functionality works fine in my code snippet, but not on my Laravel 5.5 site. No errors are showing up in my console. The HTML code goes into create.blade.php and the Vue ...

Using AJAX in Django to detect fields with JavaScript

I am currently working on a model: class Name(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...