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

Issue encountered when attempting to batch delete documents within a subcollection: Error message displays "TypeError: n.indexOf is not a

When attempting to batch delete a document within a subcollection, I encounter some issues. There are scenarios where I may need to remove the same product document ID along with various history document IDs, or multiple product document IDs with differen ...

The functionality of AngularJS's state URL depends on numerical URLs for navigation

Currently, I am utilizing the following URL in my state setup: .state('forum.spesific', { url: '/:articleId', templateUrl: 'modules/forum/client/views/forum.client.view.html', controller: 'forumCont ...

The website is displaying a strange mix of text and HTML when viewed on a PC

While browsing the internet for C programs, I stumbled upon this particular program that caught my eye: <span style='color:#004a43'>#</span><span style='color:#004a43'>include</span><span style='color:#8 ...

Modify the selected option in a dropdown using an Angular controller

I am trying to update the "selected value" of a dropdown to match the value that is already saved in the database. Is there a way to achieve this? Controller var app = angular.module('app', []); app.controller('ctrl', function($scope ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Is there a way to automatically refresh the page and empty the input fields after clicking the submit button on the contact form?

My knowledge of PHP and js is limited, so I may require additional guidance in incorporating those codes. Lately, I've been developing a contact form and making good progress. However, I'm struggling with figuring out how to refresh the page or ...

Using Angular's ui-router to pass and access parameters in your

I am currently facing an issue while using Angular with ui-router. Everything is working smoothly except for one particular scenario. I have designed a directive element that serves as the header of the page. This element consists of a menu with 4 links. T ...

Using Jquery to activate a vertical scrolling bar

Within my div, I have a tree view that extends beyond the size of the div, causing a vertical scroll bar to appear on the right side. When users click a button outside of the div, I want the page to scroll to a specific item within the div (which I know th ...

Is there a way to retrieve random data based on either product id or slug within a single component using useQuery? Currently, all components are displaying the same data

Here is the code I wrote: const fetchCartItem = async () => { if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(fal ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

An array-filled Angular post object

I'm facing an issue where I am attempting to send an object with properties and arrays in it. While the properties get submitted successfully, the arrays within the object do not get serialized back in a MVC.NET Controller. Even though the page is cor ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

What is the best way to store settings values permanently during the installation process in a react-native application?

I am looking for a way to save the settings of my app only during installation, rather than every time the app is opened, in order to prevent the options from resetting. I have tried searching on YouTube but most tutorials cover only user login persistence ...

The state remains unchanged when useState is invoked

I am currently designing a unique restaurant website template. As part of the project, I have implemented a modal box with two arrow buttons to navigate between pages. The issue I am facing is that the value of the pageNumber variable, tracked using useSta ...

Tips for validating date input in a TextBox using JQuery on an ASP.NET platform:

Here is some code I wrote: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="datetime.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <tit ...

Exploring the world of unit testing promises within JS data models in an Angular

We have integrated js-data and js-data-angular into our current project. The model we are using is as follows: (function () { 'use strict'; angular.module('dash.models') .factory('Diagnosis', ['DS', functio ...

Having trouble getting Firestore/Firebase to work with Next.js?

Hey everyone, I could really use some help here. I've been working on integrating Firebase into my Next.js app for the API. Everything works well when I build and run locally, but once I deploy to Vercel for production, I encounter a 500 - Internal S ...

Using JavaScript/TypeScript to sort through and separate two arrays

Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below: export interface IMyObjectFromAPI { status: { ...

Incorporate a new JavaScript animation as the background for an established website, replacing the static background image

Seeking assistance with my portfolio as I delve into the world of Webdesign and learn the basics from templates. How can I integrate this javascript code into the background of my site, replacing the current minecraft image? Every attempt to implement it ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...