issue with ng-selected in AngularJS not functioning

<select ng-model="dayOfMonth">
   <option value="" label="Select day"></option>
   <option ng-selected="parseInt(dayOfMonth) === parseInt(day+1)"  ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}>{{$index+1 | ordinal}} of the month</option>
</select>

My dayOfMonth ng-model is set to 12, but the default value selection based on dayOfMonth is consistently choosing the last index instead.

The getTotalDays function, shown below, simply generates an array containing 28 items.

$scope.getTotalDays = function(){
   return new Array(28);
}

Answer №1

make this a replacement:

<select ng-model="dayOfMonth">
   <option value="" label="Choose day"></option>
   <option ng-selected="parseInt(dayOfMonth) === parseInt(day+1)"  ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}>{{$index+1 | ordinal}} of the month</option>
</select>

replace it using ng-options https://docs.angularjs.org/api/ng/directive/ngOptions

similar to the following:

angular.module('myApp', [])
  .controller('myController', ['$scope',
    function($scope) {
      $scope.getTotalDays = [1, 2, 3, 5];
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <select ng-model="dayOfMonth" ng-options="day as (day + ' of the month') for day in getTotalDays">
      <option value="" label="Choose day"></option>
    </select>
  </div>
</div>

Answer №2

Using ng-selected is not necessary because the correct option in your <select> will automatically be set by ng-model. One potential problem you might have encountered is if you set dayOfMonth = 12 as an integer, while the option values are all strings. The code snippet below demonstrates how to make it work, although the | ordinal filter had to be removed as the relevant code was not provided.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.dayOfMonth = '12';
    $scope.getTotalDays = function() {
      return new Array(28);
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="dayOfMonth">
    <option value="" label="Select day"></option>
    <option ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}">{{$index+1}} of the month</option>
  </select>
</div>

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

Utilize AngularJS to sort data based on specific columns

I have a table with two columns: "Name" and "Description". In addition, I have a dropdown list containing the names of these two columns. The user needs to select one item from the dropdown list to indicate which column should be filtered, and then enter ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

Error: The jQuery Class is returning an undefined value

I have been working on creating a basic AJAX request class in jQuery. However, I've encountered an issue with the 'process' function where I can get the response from the variable 'response'. When I return 'response', it ...

Integrating component names into a tag in React

I've encountered a similar issue before, but unfortunately, the suggested solutions aren't working for me. I suspect it might have something to do with how I am conditionally rendering components. Essentially, I have a selection of choices for th ...

Modify the scope parameter within the service

One of the interesting aspects of my app is how I have structured my controllers: Main controller: app.controller('AppCtrl', ['$scope', function ($scope) { $scope.app = { amount: 0 }; }]); Child Controller: app.contr ...

Guide to verifying current data using the jQuery validation library combined with CodeIgniter 4 in the presence of automatic CSRF protection

I am currently working on validating a form using the jQuery validation plugin and CodeIgniter 4. I have enabled CSRF protection that auto generates for each request. Initially, I can successfully validate the form on the first request. However, on subsequ ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Combining Ionic 3 with epubJS

Greetings. I've been attempting to access ePub files in my Ionic 3 test app without success. epubjs has been installed via npm. Here is the package.json contents: { "name": "app_name", "author": "Author", "homepage": "http://example.com/", ...

Displaying JSON as a table using React JS

I can't seem to display JSON data in a table using the useState hook in React, and I'm not sure why. Here's a snippet from my React file: {` import React, { useState } from 'react' import "../styling/Classes.css"; import data ...

Is there a way for my Symfony2 bundle to utilize web services from a separate bundle?

We are currently in the process of developing a cutting-edge Angular JS / Symfony2 application that utilizes RESTful web services to retrieve crucial data for the frontend. In addition, we are implementing an administrative interface (non-Angular) to over ...

What is the best way to use jQuery to toggle the visibility of a <panel>?

My objective is to display a panel with two labels on a button click, but I'm facing issues achieving this functionality. When I click on the button (id=Button1), the panel (id=anspanel) should appear, but it remains hidden even after clicking the but ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

Interactive ajax and php dropdown menu

Hey there, I'm running into a small snag with my dynamic select feature, as mentioned in the title. I am aiming to achieve the following outcome: When a user selects an instrument from the first dropdown menu, the second dropdown menu labeled "Besetzu ...

Invoke a method of a child component within the parent component using Angular 1.5

I have a parent component template with a nested component within it. <div class="inner" ng-show="!vm.loading"> <div class="info-panel"> <h3 id="basePrice">Current Cost</h3> <p> <small> ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...

I am experiencing difficulty in passing parameters to nested navigators

I have developed a TechInfo page and a ProfileInfo page. The ProfileInfo Page is nested inside a Drawer Navigator. I want to display some information from the TechInfo page and some from the ProfileInfo page when I enter our info and press a button. Howeve ...

The issue with Three.Js Raycasting arises when attempting to change camera transformations within an Object3D parent element

In my latest project, I decided to create a "camera controller" that handles the movement and rotation of the camera by utilizing an Object3D as its parent. The Y-axis rotations are applied to the Object3D, while the X-axis rotation is directly applied to ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Is there a way for me to conceal my table upon clicking on the sidebar? Additionally, when I click on a button to display a different table, can the currently visible table automatically close?

I have a unique table for each button. Initially, the tables are hidden using CSS visibility: 'hidden', and when I click a button, the corresponding table displays. However, the issue arises when I click the same button again as it fails to hide ...