Setting the default dropdown option in Angular

For my latest question, I decided to utilize ng-init. However, upon loading the page, I noticed that there is a blank default option. When I click and select another option, the blank option disappears. How can I remove this initial blank option?

Here is the code snippet:

<select ng-change="filtro(selected)" ng-init="selected = Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos">
</select>

And here is the controller function:

   function cargarCatalogo() {
        apiService.get("../../api/Catalogos/", null,
            function (res) {
                console.log(res.data);
                $scope.Catalogos = res.data; 
            },
            errorCatalogo);
    }

Answer №1

Considering the timing of events, the ng-init function is executed before the ajax call returns. This means that when you set selected = Catalogos[0], the item doesn't exist yet and remains undefined. Once the ajax call completes and populates the $scope.Catalogos, the select list will display the options but still have an undefined selected option. To resolve this issue, you should set

$scope.selected = $scope.Catalogos[0];
within your ajax callback as shown below:

function cargarCatalogo() {
    apiService.get("../../api/Catalogos/", null,
        function (res) {
            console.log(res.data);
            $scope.Catalogos = res.data; 
            $scope.selected = $scope.Catalogos[0];
        }, errorCatalogo);
}

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

What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any a ...

Secure a RESTful API with a Keycloak access token in a Node.js environment

I have implemented a REST API in Node.js and integrated the keycloak-connect npm package for security. I have configured the Node.js middleware to work with the keycloak middleware. var express = require('express'); var router = express.Router(); ...

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...

Issue encountered with md-grid-list at reduced screen dimensions

I'm currently developing a mobile website that showcases products in a grid-list format. To create the grid list, I am utilizing the md-grid-list directive from Angular Material. Below is the snippet of code I wrote to implement this functionality: ...

JavaScript plugin specifically designed to enable playback of media content, such as videos from

I am working on a spring-based project and I require the ability to play audio/video in various formats similar to YouTube. I am currently searching for a free JS plugin that would be the best fit for my needs. Any suggestions or recommendations would be ...

Unable to retrieve res.user.username while using passport within express-session

I'm currently diving into the realm of creating sessions with Passport.js and Express.js. My goal is to retrieve the username from a user stored in a session using res.user.username, but I seem to be facing some challenges. Below is the snippet of m ...

The JavaScript replace function using regex eliminates additional content

There is a content string that includes full YouTube URLs and video IDs. I need to replace the URLs with just the video IDs. The example of the "content" variable: var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

"Experience the power of React Swiper 6.8.4 as it unveils its slides only during window resizing or when

I'm a beginner in the world of coding and react, and I've encountered an issue with Swiper 6.8.4 in my React app after implementing a FilterMethod. My goal was to create a Slider containing Projects/Images as Slides, allowing users to filter thes ...

What could be causing the "Undefned Jquery-ajax" error to pop up

I am struggling with the following code. My goal is to populate values into a dropdown <select> box, but I keep receiving an error of undefined. I have tried switching between Object.keys and Object.values, however, I am still facing the same issue. ...

The data input from the HTML is not being correctly transferred to the modal

I am trying to transfer the reservation id from an HTML element to a modal window. When I click "cancel" next to a reservation, a modal should appear showing the reservation id. However, the modal pops up without displaying the reservation id. Can anyone h ...

Creating an AngularJS application that can run without the need for a

Being new to AngularJS, I have a question about its functionality. As Angular is a client-side framework, it should work without a web server. However, the following code snippet doesn't seem to function correctly: <!doctype html> <html ng-a ...

How can I incorporate dynamic fields into a Typescript type/interface?

In my Typescript interface, I have a predefined set of fields like this: export interface Data { date_created: string; stamp: string; } let myData: Data; But now I need to incorporate "dynamic" fields that can be determined only at runtime. This me ...

How can we prevent and remove extra whitespace characters such as new lines and line feeds in responseText?

I am troubleshooting an ajax script that is calling a php file. The php file is supposed to echo either "yes" or "no", which I intend to use for logical comparisons. However, when trying to compare the responseText in javascript to check if it matches "y ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...

Problem uploading files with ajax in Laravel version 6

I am encountering an issue while attempting to save a PDF file along with other input values using Ajax in Laravel 6 without utilizing the form HTML element. The error message "Call to a member function getClientOriginalExtension() on null" keeps popping u ...

Using spin.js instead of an animated gif provides a sleek and modern alternative for adding loading

Seeking guidance as a newcomer to JQuery. A form "processing" div should appear after form submission. Currently, using a basic div with an animated gif for visual feedback: <div id="loading">Please wait, your news is being submitted... <img src= ...

Which medium is the optimal choice for file manipulation in Node.js and JavaScript?

Is there a simple way for JavaScript to receive incoming data from Node.js that was obtained from an external server? I've been searching for a solution to this problem for days now. Here's my current approach: I plan to have both the server-sid ...

How can we send data from several input fields using jQuery ajax?

I have several input fields, such as <p>Filter by age</p> <select class="filter-users"> <option value="under20">Under 20</option> <option value="20to40">20 to 40</option> </select> <p& ...

Avoid deleting a row in Sequelize if it is referenced in another association

Is there a method in Sequelize.js to trigger an exception when attempting to delete a row that is associated with another entity? For example, consider tables for Roles and Users. They have a many-to-many association, allowing any user to have multiple ro ...