Dynamically setting the default selection in a dropdown menu

When choosing a default value from a dynamically populated dropdown using JSON data, I attempted to use regCtrl.screeningTypeList[0] without success.

<select ng-init="regCtrl.user.screeningType.screeningTypeId=regCtrl.screeningTypeList[0]" ng-model="regCtrl.user.screeningType.screeningTypeId" ng-change="regCtrl.getType(regCtrl.user.screeningType.screeningTypeId)"
                                 ng-options="sctype.screeningTypeId as sctype.screeningType for sctype in regCtrl.screeningTypeList"
                                 class="form-control field-size ng-pristine ng-invalid ng-invalid-required ng-valid-maxlength ng-touched" name="screeningType"
                                 id="screeningType"  required >
                                <!--  <option value="">--SELECT--</option> -->
                                <!--  <option value="{{sctype.screeningTypeId}}">{{sctype.screeningType}}</option> -->
                              </select>

The above code snippet represents the AngularJS logic for fetching and displaying JSON data.

function getScreeningTypeList(){
            $http({
                method: 'GET',
                url: 'master/getAllScreeningTypeMast'
            }).success(function(response){
                vm.screeningTypeList=response.result;
            }).error(function(resp){

            });
        }

This is an example of controller-related code where the 'vm' value is initialized at the beginning.

 RegistrationController.$inject = ['$http','LookupService','$filter'];
    function RegistrationController($http,LookupService,$filter){
        var vm = this;
}

Answer №1

        $http({
            method: 'GET',
            url: 'master/getAllScreeningTypeMast'
        }).then(function(res){

            vm.screenTypes=res.data.result;
            vm.user.current.typeId = vm.screenTypes[0];
        }).catch(function(error){

        });

ALSO delete ng-init directive from the element.

Answer №2

If you want to assign the value to your model after making an http request, here are a couple of options:

function getScreeningTypeList(){
            $http({
                method: 'GET',
                url: 'master/getAllScreeningTypeMast'
            }).success(function(response){
                vm.screeningTypeList=response.result;

$scope.regCtrl.user.screeningType.screeningTypeId=vm.screeningTypeList[0];  // You may need to replace $scope with vm in your case
            }).error(function(resp){

            });
        }

Alternatively, you can create a function and use ng-init:

Function nginitSelect(){
  $scope.regCtrl.user.screeningType.screeningTypeId= $scope.regCtrl.screeningTypeList[0]; // You may need to replace $scope with vm in your case
}

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

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...

Is there a way to target a button within an anchor tag without relying on a specific id attribute?

On my webpage, I have buttons that are generated dynamically using PHP from a MySQL table. Each button is wrapped in an anchor tag and when clicked, it triggers a Javascript function to carry out multiple tasks. One of these tasks requires extracting the ...

Unable to retrieve file path from image selection in JavaScript by clicking on a button

I am trying to create a simple browsing feature that only accepts images. However, after clicking the button, I am unable to retrieve the full path in JavaScript. All I can get is the filename. JavaScript <script type="text/javascript"> functio ...

How can I export an ES Object in Node.JS to an NPM package?

I am currently facing a challenge involving an ES5 object/function that I want to integrate into an NPM package. This particular object is within a namespace defined as MY_NAMESPACE.myObject = function(){...} where MY_NAMESPACE is simply an object. Typic ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

An unexpected issue occurred during runtime, specifically a TypeError stating that the function posts.map is not

Currently, I am diving into the world of nextjs and decided to follow a tutorial on building a Reddit clone that I stumbled upon on Youtube. However, I encountered a persistent issue: posts.map is not a function I would appreciate any assistance you can o ...

Can you include variables at the start of the URL using ui-router?

Is it feasible to include a variable in my route setup like below: $stateProvider .state('edit', { url: ':organization/edit', templateUrl: 'partials/edit.html', controller: 'editController&apo ...

Encountered an issue when attempting to access a file on the desktop using Node.js

Here is the code I am using to read a simple file from my desktop: module.exports = function (app) { app.get('/aa', function(req, res) { fs = require('fs'); fs.readFile('‪C:\\Users\\t5678 ...

Sending an image dynamically as a prop to a child component

Within my parent component, I retrieve an object from an API which I later enhance with an image as a key/value pair. Subsequently, I pass this modified object to a child component for rendering. In order to accomplish this, I referred to the following pos ...

display a dropdown menu with a default selection

Trying to pre-select a value in a dropdown from database but facing issues. Need assistance in resolving this problem. HTML <select class="form-control" ng-model="reportType.consolidationScopeId"> <option value="">Please select</option& ...

creating styles for css elements using equations

I am curious about defining CSS element dimensions before they are rendered without using offset and jQuery. Is it possible to echo PHP into the width/height or position values? For example: <?php $width = 290px; $altwidth = 290; ?> <style> ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

Sign up for a new magazine or newsletter once your current one has been fully processed | React-Meteor

Currently, I am working with two publications: teams.dashboard and boards.board. My goal is to load the boards.board publication using the boardId from the first loaded Board, which can be accessed like this: Boards.find().fetch()[0]._id. I'm searchi ...

I am seeking to transform an elongated image into a two-dimensional circle using WebGL. This process will involve intentional distortion of the image

Trying to figure out how to take a high-resolution image and wrap it into a circle has been a challenge. It's like bending a steel bar until it forms a perfect circle with both ends touching. I've been grappling with threejs for the past 8 hours ...

Revamping the settings page by featuring a single "save changes" button

Is it possible to create a settings.php page where users can update their personal information, such as username, password, and email, all within the same page? I know how to perform these tasks individually, but I'm unsure about integrating different ...

What is preventing the click function on a dynamically created button from being executed in jQuery?

Take a look at this jsFiddle where I illustrate my issue. Whenever I click on the "Add an ingredient" button, the button click event is triggered. My issue arises when I click on the "Create a subtitle" button because it dynamically creates "Add an ingredi ...

Transform PHP array into a properly structured array or object that can be easily used in JavaScript

My PHP code contains an array that looks like this: $variation = [ attribute_label => "Choose your Color", attribute_name => "pa_choose-your-color", variations => [ "819" => "Red", "820" => "Blue", ...

The body tag mysteriously disappears after the function is called within the $().html() command

As I delve into scraping the source code of a website, I encounter an interesting phenomenon. Initially, when I print out the complete source code, everything appears as expected. However, upon attempting to print an actual DOM, I notice a slight change i ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...