Unable to designate the drop-down option as the default selection

Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this.

You can find my code on jsFiddle

<div ng-controller="csrClrt">

    <div ng:repeat="(key, item) in items track by $index">

        <md-input-container>
            <label>Face Style:</label>
            <md-select ng-model="item.style" ng-change="f_style()" ng-model-options="{trackBy: '$value.id'}">
                <md-option ng-value="user" ng:repeat="user in styles">{{user.name}}</md-option>
            </md-select>
        </md-input-container>
        <div>
            Id:{{item.style.id}}
            <br/> Want to Display Name {{item.style.name}}
        </div>
    </div>


</div>

JavaScript Code

angular.module('MyApp', ['ngMaterial'])
.controller('csrClrt', function ($scope) {
    stylesdata = [{
            name: "a",
            id: 0
        }, {
            name: "b",
            id: 1
        }, {
            name: "c",
            id: 3
        }
    ];
    $scope.items = ["0"];
    var style = [];
    for (var i = 0; i < stylesdata.length; i++) {
        style.push({
            name: stylesdata[i].name,
            id: stylesdata[i].id
        })
    }
    $scope.styles = style;
})

Answer №1

You have incorrectly set up the items object and do not need to use

ng:repeat="(key, item) in items track by $index"

Check out this view:

<div ng-controller="csrClrt">
    <md-input-container>
        <label>Face Style:</label>
        <md-select ng-model="items.style" ng-change="f_style()" ng-model-options="{trackBy: '$value.id'}">
            <md-option ng-value="user" ng:repeat="user in styles">{{user.name}}</md-option>
        </md-select>
    </md-input-container>
    <div>
        {{items.style}}
    </div>
</div>

Here is the correct controller setup:

$scope.items = {
    style: {
        id: 1
    }
};

Check out the updated Fiddle here!

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

The image zoom function is malfunctioning when trying to adjust the image position

Having some trouble with a code for image zoom in/out. When I adjust the position of the image by applying margin left to either the image or the image container (#view), it affects the zoom functionality - causing the image to move to the left during zoom ...

The Vue production build displays a blank page despite all assets being successfully loaded

After running npm run build, I noticed that my vue production build was displaying a blank page with the styled background color from my CSS applied. Looking at the page source, I saw that the JS code was loading correctly but the content inside my app d ...

Update the AngularJS (1.5) application to Angular 5

Looking for advice on transitioning an AngularJS app to Angular (in this case, version 5). I've been exploring the official documentation, but I still have some uncertainties. From what I gathered in the guide, it suggests migrating from AngularJS by ...

Troubleshooting steps for resolving Heroku's "State changed from up to crashed" error caused by Mongoose connection issue

I am encountering an issue while deploying my Node.js/MongoDB app to Heroku. It crashes with the following error: MongooseServerSelectionError: connection <monitor> to 104.155.184.217:27017 closed Below are excerpts from my log: 2022-07-10T23:36:17. ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

instructions on how to exclusively close a bracket within a double bracket in a regular expression match

const input = "example(1)(2)example(3)example(4)(5)example(6)(7)example(8)example(9)" const regexp = new RegExp(????) // <-- need help with this input.match(regexp) result: [example(1)(2), example(3), example(4)(5), example(6)(7), example(8), example( ...

Encountering a loading error with r.js while attempting to optimize

In my main.js file, I have the following configuration for Require.js: /*--- Setting up Require.js as the main module loader ---*/ require.config({ baseUrl: '/javascripts/libs/home/', waitSeconds: 0, paths : { jquer ...

Products failing to appear in shopping cart

I'm facing an issue with my React Redux Cart setup where items are added to the cart state using the addItem action, but they do not appear on the Cart page. Challenge: After adding items to the cart through the addItem action, I can see the state u ...

How can we activate navigation on a mobile browser?

I am currently working on a small HTML5/JavaScript website designed to be accessed by mobile browsers on devices such as Android and iPhone. I am utilizing the geolocation feature of HTML5 to obtain the user's current location, but my goal is to then ...

Can a value be concealed within a dropdown list on a form (using PHP or JavaScript)?

Within my form, there is a drop down box listing the 50 states in the U.S. This list is generated using a PHP for loop. Users are required to select their residential state and later on, they must also choose a mailing state if it differs from their resi ...

Transform JSON structure (Group data)

Here is the JSON object I am working with: [{ "name" : "cat", "value" : 17, "group" : "animal", }, { "name" : "dog", "value" : 6, "group" : "animal", }, { "name" : "snak", "value" : 2, "group" : "animal", }, { "na ...

`Jump-start Your Development with jQuery Lightbox Centering`

Recently, I implemented a lightbox effect for images on my website. However, I encountered an issue where the lightbox was not centering properly in the window upon initial click. Instead, the lightbox would appear at the bottom of the page on the first cl ...

The table refuses to load

I've been troubleshooting this issue for the past two days. The array is visible in the console, but it refuses to show up on the table. I've tried multiple approaches, but none seem to work. I suspect that "tobodyHtml" is not defined properly, a ...

Adding query parameters to the end of every link on a webpage

Wondering how to automatically add GET values to the end of each anchor href on a webpage? For instance, if you input google.com?label=12&id=12 I want to ensure that "?label=12&id=12" gets added to the end of every single href in an anchor tag on ...

Continuous Scrolling with Callback Function in jQuery

I have implemented the infinite-scroll plugin, which replaces traditional pagination with ajax to fetch new pages. The issue I am facing is that jQuery functions do not recognize the new posts, causing certain functions like the ones below to stop working ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Is it possible to include personalized validations in Formik's YupValidationSchema?

Is it possible to include custom validations in Formik's YupValidationSchema as shown below? YupValidationSchema = () => { return Yup.object({ Email: Yup.string() .max(256, "Length exceed 256 chars") ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

The nearby diversion inexplicably triggers a phantom GET request

My goal is to build a website with specific functionality: If a user tries to access the /home page without authentication, they should be redirected to the /login page. After successfully logging in on the /login page, the user should receive a session c ...