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

Running JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common f ...

Limit the Datepicker in MUI (v5) to only accept two-digit years

I am currently using the MUI (v5) Datepicker for capturing user birthday information. The Datepicker has been localized to German language, resulting in the input format DD.MM.YYYY. However, many German users prefer using a shorter year format like DD.MM. ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Modification of a CSS element

The CSS I am working with looks like this: .cls .imageX { float:left; } .cls .imageY { float:right; } It is currently being used on a page in this way: <div class="cls"> <a href="" class="imageX"><img src="left.png"/></a> &l ...

Implementing Asynchronous Custom Validators in Angular 4

I've encountered the following code snippet: HTML: <div [class]="new_workflow_row_class" id="new_workflow_row"> <div class="col-sm-6"> <label class="checkmark-container" i18n>New Workflow <input type="che ...

Can you explain the extent to which JavaScript's setTimeout() and clearTimeout() apply?

Approximately 30 seconds after a page is loaded or reloaded, a pop-up will be displayed under certain conditions. The following code successfully achieves this functionality: jQuery(document).ready(function($) { .......... if (localStorage.getItem ...

How to apply props conditionally in VueJS?

I have a component called blogPost (Component A) that is imported in another component named B. When a button in Component B is clicked, Component A opens in a modal. There are two different use cases for this scenario. 1. One case requires passing 2 prop ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Vows, Tobi, and Node.js come together for comprehensive REST API testing

Currently, I am in the process of merging the examples here and here to create a vows test for my node.js / express application that does the following: Creates a new user object Verifies that the response is correct Utilizes the returned _id to perform ...

Posting and deleting data in AngularJS using HTTP requests

Incorporating both angularjs and c# webapi in this situation. My approach involves calling the webapi from angularjs and passing a json array. Here is the Angularjs code snippet: factory.delete = function (json) { var url = 'myUrl'; ...

A quick guide on automatically populating text boxes with characteristics of the item chosen from a drop-down menu

On my webpage, I am looking to automatically populate textboxes with information (such as common name, location, etc.) of the selected shop from a dropdown list without having to refresh the page. Here is the dropdown list: <select id="shops" class="f ...

Update the styling for the second list item within a specified unordered list class instantaneously

Looking to emphasize the second list item (li) within a selected dropdown list with a designated unordered list class of "chosen-results". <div class="chosen-container chosen-container-single select-or-other-select form-select required chosen-proc ...

Angular ng-bind is incorrectly displaying the value as 'object' instead of the intended value

I am working on an Angular app where I am retrieving data from a service in the following manner: angular.module('jsonService', ['ngResource']) .factory('MyService',function($http) { return { getItems: ...