Tips for setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options?

Consider the items we have:

$scope.items = [{
  id: 1,
  label: 'aLabel',
  subItem: { name: 'aSubItem' }
}, {
  id: 2,
  label: 'bLabel',
  subItem: { name: 'bSubItem' }
}];

The HTML code would be:

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>

Instead of selecting the option with:

$scope.selected = $scope.items[0];

If I only have the ID information, I want to initialize the select with something like this:

$scope.selected = $scope.otherRandomObject.id 

I believe that using track by item.id establishes the connection between the object and its ID.

Answer №1

When looking to set a default value, the ng-selected directive can be utilized

<select ng-options="option as option.text for option in options" ng-selected="$first"></select>

By using ng-selected="$first", the first option in the array will be automatically selected

Trust this explanation has clarified your query

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

I am currently using React to implement a feature that displays random facts for 5-second intervals. Despite no errors being displayed, the facts are not appearing on the page as expected

Client side My react application includes a section that is supposed to display random facts at 5-second intervals. Although no errors are displayed, the facts do not appear on the page when I run the code. import React from "react"; import &quo ...

Guide on modifying an angular-material directive and compiling it

When I compile a native HTML element, everything works perfectly fine. However, when I try to compile an Angular Material element (md-button), the console displays an error message: "Error: [ngTransclude:orphan]". I've reached a point where I am com ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

The input type file is not correctly inserting an image into the image tag

While I was working on a project, I had a question that got answered but now I need to find a different way to use the solution. I have created a jsFiddle to demonstrate how it currently works. You can view it here: http://jsfiddle.net/TbZzH/4/ However, w ...

Unable to apply 100% height to flex child element

When it comes to creating a layout for my website, I have a simple idea in mind. I want the body content to take up at least 100% of the height of the page. This setup works perfectly on desktop screens, but when I switch to a mobile view (which changes th ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

Center Align Images in HTML List Items

Hey there! I'm currently diving into the world of web development with responsive design, but I'm still a bit of a newbie. So please bear with me as I try to explain my issue in detail. If you need more information, just let me know! My current ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Steps to customize Button Color and Label in a specific cell within a Material UI Table

I've implemented the Material Table to display my data, and it seems like this: In my code, I have a declared state as follows: const [sharedOrdersList, setShareOrdersList] = useState([]) When the User clicks the Share button, I push the Order Id in ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

AngularJS: incorporating various functionalities within a single controller

I have a basic AngularJS controller that I am working on, and I would like it to include two separate functions: var app = angular.module('searchApp', []); app.controller('searchCtrl', function($scope, $http, $log) { //Function 1 ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

Receiving messages in AngularJS with the help of Strophe.js

My XMPP client in AngularJS, inspired by this stackoverflow link. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d282e382f1d282e382f7331323e3c31">[email protected]</a> can send messages successfully, but <a hr ...

Is there a possibility of encountering an endless update loop within a component's render function?

Hello! I am a beginner in Vue.js and I have encountered an issue with my function. Instead of increasing my variable to 1 as expected, it is increasing it to a random number every time. The console is displaying the following error message: "You may hav ...

Is fs-extra the best tool for working with a .bundle file?

I am attempting to determine whether a specific folder in my project includes a .bundle file and, if it does, relocate it to another location. If the file is not found, I will use a default option instead. The problem I'm encountering is that I am una ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Two functions are contained within an object: Function A and Function B. Function A calls Function B from within its own code

If I have two functions within an Object. Object = { Function1() { console.log('Function 1') }, Function2() { this.Function1() } } The Function1 is not being executed. Can someone explain why this is happening an ...

Having issues with images not loading and receiving a 401 error with the API while using Vite in a production build

While working on my React project with Vite, I've encountered a few challenges during the production build process. Everything seems to be running smoothly when I use npm run dev, but when I try to build the project using npm run build and then previ ...

What methods can be used to construct components using smaller foundational components as a base?

Is there a more elegant approach to constructing larger components from smaller base components that encompass common functionalities, akin to an interface in the OOP realm? I'm experimenting with this concept, but it feels somewhat inelegant. Repor ...

Unable to stop interval in Angular 5 application

My setInterval() function seems to be working fine as the timer starts, but I am encountering an issue with clearInterval(). It does not stop the timer when the counter value reaches 100 and continues running continuously. Any help or suggestions would be ...