angularjs select not chosen option

Hey there, I'm currently attempting to select an item from an array in the select options by using a string value.

Below is my HTML code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="AppCtrl" ng-app="myApp">
  <select ng-model="gender" ng-options="g.vl as g.lbl for g in genders track by g.vl">

  </select>
</body>
</html>

Here's the JavaScript code:

var app = angular.module('myApp', []);

app.controller('AppCtrl', function($scope) {
  $scope.genders = [ {lbl: 'Male', vl: 'male'}, {lbl: 'Female', vl: 'female'}];

  $scope.gender = 'female';
});

It works fine without the "track by" clause and selects the initial value, but I need to include it to use the value from the database (though it currently selects an empty option). Is there a workaround for this issue without looping through the options and comparing the initial value? Thank you! Here's the snippet of the code http://jsbin.com/qixad/4/edit

Answer №1

Utilizing the track by feature in Angular allows the framework to determine similarity based on a specific property specified in the track by expression. To set up the gender initialization, simply assign it an object with the vl property defined:

$scope.gender = {vl:'female'}; //OR
$scope.gender = $scope.genders[1];

Moreover, the key in the ng-options expression should represent the model itself.

<select ng-model="gender" ng-options="g as g.lbl for g in genders track by g.vl">
</select>

JS Bin Demo

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

Page refresh problems

Hey, I'm facing an issue with page refresh. Every time I hit the refresh button on the browser while on a page other than the index, I encounter a "Server Error in '/' Application." 404 error Page. The back forward button works fine, but th ...

Improving "time elapsed" values with AngularJS and MomentJS

Rephrased: I am faced with a challenge where I have a dynamically generated table using ng-repeat, containing numerous entries with various Unix timestamps. To humanize these timestamps and display them as "19 minutes ago" or similar time references, I a ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

Issues encountered when rendering textures from a canvas in Three.js

I've been working on creating a texture from a canvas. I managed to successfully render a blank canvas, but encountered issues when trying to draw an image on the canvas and then render it. This is the code snippet I am currently using: var canva ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Vuejs method to showcase input fields based on form names

I am working on a Vue.js form component with multiple input fields, but now I need to split it into two separate forms that will collect different user input. Form 1 includes: Name Surname Email with a form name attribute value of form_1 Form 2 i ...

Can you explain the difference between synchronous and asynchronous loading?

After exploring this website, I have learned that when using CommonJS, the browser loads files one by one after downloading them, which can lead to dependencies slowing down the process. However, with AMD, multiple files can be loaded simultaneously, all ...

Automatic closure of Info Window on Google Maps is not functioning as expected

I have recently developed a map which you can view here. The issue I am facing is that when I click on the layers to see the InfoWindow, they do not automatically close when I click on another layer. The JavaScript code I am using is causing this problem. ...

How can I convert a string number with leading zeros into a string in a node.js environment?

When rendering a page, I pass the id as a string (e.g. 001, 002) but at the client side, I receive it as a number (e.g. 1, 2). res.render('leafletDemo',{id:userID,latitude:latitude,longitude:longitude}); Is there a way to keep the id as a str ...

Verify if a particular string is present within an array

I am in possession of the key StudentMembers[1].active, and now I must verify if this particular key exists within the following array const array= ["StudentMembers.Active", "StudentMembers.InActive"] What is the method to eliminate the index [1] from Stu ...

What is the best way to achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

The combination of Nest, Fastify, Fastify-next, and TypeOrm is unable to locate the next() function

In my attempt to set up Nest with Fastify and Next using the fastify-next plugin, everything went smoothly until I added TypeOrm for MongoDB integration. Upon loading the AppModule, Nest throws an error indicating that the .next() function cannot be found ...

What is the most effective way to redirect users accessing from Android devices?

Attempting to send all Android users to a designated page. I attempted this method using php, but uncertain of its reliability. Need assurance that it will work for all possible Android devices. Thoughts on the safety of this approach? <?php $user_ag ...

Having trouble receiving a callback after sending an AngularJS $http.post request

I am experiencing a problem with the success/fail handlers not being called when making an Angular $http.post request. The server side of my application is a .NET MVC controller, which successfully receives the file and functions correctly in that aspect. ...

Engaging with the crossrider sidepanel extension

When it comes to the crossrider sidepanel, I prefer using an iframe over js-injected html to avoid interference with the rest of the page. However, I am struggling to establish any interaction between my browser extension and the iframe. I believe adding ...

Performing a POST request using XMLHttpRequest with parameters in an asp.net environment

I am working on utilizing a javascript XMLHttpRequest object to send a post request to my action method. Here is my current setup: xmlhttp.open('POST', '../Employees1/HandleFileUpload', true); My action method does not currently take ...

Using the arrow keys to navigate through a list of items without using jQuery

Exploring ways to develop a basic autocomplete feature without relying on third-party dependencies has been my recent project. So far, I have managed to populate a results list using an ajax call and complete fields with mouse onclick events for each optio ...

AngularJS directive's watch function is returning undefined values for both the newValue and oldValue

My goal is to create an alert system using a directive. I am using a service to manage all the alerts in my application, and a directive to display them. I have implemented a watch in the directive to apply a timeout for alerts that should disappear automa ...

What is the code to convert data to base64 in Javascript when it is not a string?

I am in the process of transferring functionality from an Objective-C iPhone application to a JavaScript iPhone application (using Appcelerator Titanium). In my Objective-C code, I have an NSData object that represents a specific token: //NSData object sh ...