Setting a default value in a dynamic dropdown using AngularJS

I could really use some assistance with my issue as I am fairly new to working with AngularJS. My dilemma is related to setting the default value in a select option when there is only one item available due to it being a dynamic select option. Though there is another dropdown with multiple items which works fine, the challenge lies in selecting the default value when there's just one item in the select option using ng-options.

                    <select  class="form-control form"  ng-model="relatedTo" style="height: 40px;" ng-options="c.CUSTCODE as c.CUSTNAME + ' - ' + c.CUSTCODE for c in customers | filter:code" >  </select><span style="color:red" ng-show="type === 9 || type !== 9"></span>

ANGULARJS

                    $http.post('commandCenter.aspx/allCustomer', {}).then(
                        function onSuccess(response) {
                            $scope.customers = JSON.parse(response.data.d);
                            console.log($scope.customers); },
                        function onError(response) {
                            console.log('error !!! ');
                        });

Picture no.1 It's okay in this picture because he has a lot of list of items.

Picture no.2 When there is only one item, it must be default or selected. https://i.sstatic.net/n1hTC.png https://i.sstatic.net/rXMqx.png

Answer №1

As suggested by @MrJami, the code would look something like this:

                $http.post('commandCenter.aspx/allCustomer', {}).then(
                    function successCallback(response) {
                        $scope.customers = JSON.parse(response.data.d);
                        if ($scope.customers.length === 1) {
                          $scope.relatedTo = $scope.customers[0].CUSTCODE;
                        }
                        console.log($scope.customers); },
                    function errorCallback(response) {
                        console.log('Error occurred!');
                    });

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

When using the executeScript() method, it unexpectedly gives a null result instead of allowing me to scroll

The following code snippet is used to scroll horizontally within a web page: WebElement element=driver.findElement(By.xpath("//div[@class='table-wrapper']")); JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("arguments[0].scroll ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Insert the META tag data specific to Facebook Instant Articles directly within the JavaScript code

My website is running on a custom-built CMS provided by a company, and it seems like a modified version of WordPress. They are unwilling to include a basic meta tag in our HTML code. I am looking for guidance on how I can incorporate Facebook's Insta ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

encountering a type mismatch error while trying to retrieve data from an array

While attempting to retrieve data from a nested array, I encountered the error "TypeError: Cannot read property 'value' of undefined". It seems like I might be calling back incorrectly as I am receiving both the output and the error message in th ...

Using CSS to design a table-like structure with rows that span multiple columns

I am trying to generate a table dynamically using CSS and a JSON array. For example: In the code snippet provided, I have assigned a class of 'spannedrow' to span certain cells in the table, although the class is not defined yet. This is just ...

Troubleshoot AngularJS in Visual Studio (but not in Visual Studio Code)

Are there any methods for debugging AngularJS code within Visual Studio other than VS Code? I am specifically interested in setting breakpoints and analyzing the code. While I am aware that there are other IDE's that offer this functionality, I am cur ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

Stop jQuery Tab from Initiating Transition Effect on Current Tab

Currently, I am utilizing jQuery tabs that have a slide effect whenever you click on them. My query is: How can one prevent the slide effect from occurring on the active tab if it is clicked again? Below is the snippet of my jQUery code: $(document).read ...

Alter the td styling depending on the value using AngularJS

I need to dynamically change the style of each td in a column based on its value. There are five different statuses, so each status should have a unique border-color and font-color assigned to it. How can I achieve this using Angular script without hard-co ...

Developing an interactive form for instant price calculations

I'm currently tackling a project that involves developing an order form capable of computing the price of a door in real-time. However, I am having trouble deciding on the best approach to take. The form will include the following inputs: Frame (Dr ...

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...

Dealing with a surprise JSON error in Express.js using Javascript

Dealing with Unexpected JSON in my express js application using try and catch. I attempted to achieve this as follows: try{ let body = JSON.parse(req.body); }catch(e){ res.json({ error:e }) } However, the Unexpected JSON error is not caught in ...

Guidelines for incorporating a router into the title of a Vuetify.js toolbar

I am currently utilizing vuetify.js in my project and I encountered an issue. I wanted the application title to link to the top menu, but when navigating to /route shop and /discount, the HogeHoge button's state changed unexpectedly. Is there a soluti ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

Determining the Nearest Form to an Element using jQuery

I developed a JavaScript/jQuery script that allows me to check all checkboxes within a form. The function works effectively, but the issue is that it checks all checkboxes on the page regardless of their form wrapper. Here is the function: function toggl ...

Leveraging JSON in conjunction with AJAX and Python database operations

I am a beginner in Python and I am attempting to access the database through Python in order to retrieve results in a JSON array using AJAX. When I test it by returning a JSON list and triggering an alert in JavaScript, everything works fine. However, as ...

How can I position an object in Three.js to perfectly align with the left half of the screen, adjusting both its width

When the button is clicked, I want the entire 3D object's width and height to adjust to fit on the left side of the screen, while displaying a div HTML info on the right side. How can I make the object fit on the left side of the screen? Can I use ma ...

Selecting images using jQuery

Currently, I am in search of a jQuery image picker plugin that possesses the following features: Show a collection of images and enable the user to select one (and only one) by clicking on it If the user dislikes any of the pre-defined images, they shoul ...