Having trouble setting a default value in a dropdown using ng-model and ng-repeat or ng-select in AngularJS?

Just diving into the world of AngularJS and absolutely loving it! However, I'm currently facing an issue with initializing a preloaded dropdown with a specific value.

The dropdown is prepopulated with values from a JSON array, but when attempting to select a default value, it doesn't visually show as selected even though the ng-model variable is correctly set.

I've put together a plunker example here http://plnkr.co/edit/7su3Etr1JNYEz324CMy7?p=preview to demonstrate what I'm trying to achieve, but I can't seem to make it work. I've tried using ng-repeat and ng-select without success. In this example, I also attempted to set the ng-selected property.

Here is a snippet of my HTML:

<body ng-controller="MySampleController">
  <select name="repeatSelect" id="repeatSelect" ng-model="SelectedStatus" ng-init="SelectedStatus">
    <option ng-repeat="option in StatusList[0]" value="{{option.key}}" ng-selected="{{option.key==SelectedStatus}}">{{option.name}}</option>
  </select>

  <select name="repeatSelect" id="repeatSelect" ng-model="SelectedOrigin">
    <option ng-repeat="option in OriginList[0]" value="{{option.key}}" ng-selected="{{option.key == SelectedOrigin}}">{{option.key}} - {{option.name}}</option>
  </select>

  <pre>Selected Value For Status: {{SelectedStatus}}</pre>
  <pre>{{StatusList[0]}}</pre>
  <pre>Selected Value For Origin: {{SelectedOrigin}}</pre>
  <pre>{{OriginList[0]}}</pre>
</body>

And this is the code snippet from my controller:

function MySampleController($scope) {

        $scope.StatusList = [];
    $scope.OriginList = [];    
    $scope.ServiceCall = {};
    $scope.EntityList = [];

    $scope.SelectedStatus = -3;
    $scope.SelectedOrigin = 1;

        var myList = [
            {
                item: 'Status',
                values: [{ key: -3, name: 'Open' },
                         { key: -1, name: 'Closed' }]
            },
            {
                item: 'Origin',
                values: [{ key: 1, name: 'Origin1' },
                            { key: 2, name: 'Origin2' },
                            { key: 3, name: 'Origin3' }]
            }
        ];

      $scope.documentsData = myList;
      angular.forEach($scope.documentsData, function (value) {
            $scope.EntityList.push(value);
            switch ($scope.EntityList[0].item) {
                case 'Status':
                    $scope.StatusList.push($scope.EntityList[0].values);                    
                    $scope.EntityList = [];
                    break;
                case 'Origin':
                    $scope.OriginList.push($scope.EntityList[0].values);
                    $scope.EntityList = [];
                    break;
            }

        });
}

Any assistance would be highly appreciated!

Thank you in advance.

Answer №1

Consider utilizing ng-options instead of ng-repeat + option for a more efficient option that still allows the default value to work seamlessly.

<select name="repeatSelect" id="repeatSelect"
        ng-options="opt.key as opt.key+'-'+opt.name for opt in StatusList[0]"
        ng-model="SelectedStatus"></select>`

To enhance readability, you can define the option label as a function within the scope.

HTML:

ng-options="opt.key as getOptionLabel(opt) for opt in StatusList[0]"

Controller:

$scope.getOptionLabel = function(option) {
  return option.key + " - " + option.name;
}

Explore a demo on Plunker: http://plnkr.co/edit/7BcAuzX5JV7lCQh772oo?p=preview

Answer №2

When using a select directive without ngOptions, the value is always a string.

To make it work, set it up like this:

$scope.SelectedStatus = '-3';
$scope.SelectedOrigin = '1';

For more information, check out the detailed answer ng-selected does not work with ng-repeat to set default value

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

translucent three.js texture with shader material

I'm currently using a circular texture to display particles: The circle texture contains transparent pixels. I'm leveraging ShaderMaterial and BufferGeometry to assign custom sizes and colors to each node. However, I'm encountering issues w ...

Encountering a problem when trying to map a List with a button in ReactJS

As I map results from a GET request, everything displays correctly - each User's picture, name, and the correct label on the button. However, the issue arises when I try to access specific user information by clicking on the button; instead of retriev ...

Tips for optimizing the processing speed of large XML files using jQuery, Javascript, and PHP

Currently, I am developing a store overview page that displays about 20 products per page. The data for this page is sourced from a zipped (gzip) XML file (*.xml.gz). You can find the feed here: . Every day, I download this file to my server using PHP and ...

Using Jquery slideToggle is creating additional spacing between inline-block divs

I am struggling with displaying a list of cities in an inline format. <div class="accordion-container"> <a href="#" class="accordion-toggle">London</a> <div class="accordion-content"> <p>Inform ...

How does jQuery create a hover effect that changes the background color of a link and keeps it when the mouse hovers over a

I'm attempting to add a background color to the main link that displays a sub-menu. Currently, only the sub-menu is visible, and as soon as the mouse moves away from the main link, the color reverts back to the original background color. <nav& ...

"What is the best approach for setting up an Azure Web App to host both an Express static site and API

Setting up an Express app was a breeze for me, but when it comes to deploying it on Azure Web App, I'm hitting some roadblocks! The structure of my app is quite simple: a static web app with its own API. Requests to /website.com/api are forwarded to ...

I'm experiencing difficulties with a JavaScript slideshow in Vegas

After installing the vegas jQuery plugin to my project using npm, I encountered issues when attempting to use it according to the documentation. Despite linking the required vegas.min.js and vegas.min.css files in my HTML, the plugin doesn't appear to ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Tips for adding information to a PHP file

Previously, I used PHP to append form data to a JSON file. Currently, I am working on a PHP file instead of a JSON file with two parameters, as shown to users in the figure below. Image URL Link My Form: <form action="process.php" method="POST"> ...

Setting isolated scope parameters can be done in a variety of ways

Here is the directive definition I have created: myApp.directive('myCategory', [function () { return { restrict: 'E', scope: { category: '=someCategory', }, templateUrl: 'category.html', ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Issue encountered while trying to update field using dynamically created row

I am encountering a problem while trying to update the unit cost and total cost of dynamically generated rows in an inventory form that submits inventories to a database. The product names are fetched via autocomplete jQuery, as shown in the snapshots belo ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

Utilizing ng-change in an AngularJS directive with isolated scope to transition towards a component-based architecture. Let's evolve our approach

I've been struggling to get ng-change to trigger in my directive with an isolated scope. I'm working on transitioning from ng-controller to a more component-based architecture, but it's turning out to be more difficult than I anticipated. I ...

Utilizing ASCX to trigger JavaScript functions within an ASPX page

I created a user control named MyListSelect.ascx that contains a list of radio buttons... <%@ Control Language="C#" %> <select> <option disabled selected>Select Options</option> <option> option 1 </opti ...

'view' is not recognized as a valid property of the 'div' element in Ionic3, so it cannot be bound

I am a beginner with Ionic and I'm trying to incorporate Angular Calendar into my Ionic3 application. However, I am encountering an error that says, "Can't bind to 'view' since it isn't a known property of 'div'. Here&ap ...

Are JSON-Web Tokens (JWTs) used for both verifying identity and granting access privileges?

Currently, I am exploring the process of developing a blog website that permits users to log in and perform tasks such as editing or deleting their own blogs based on their user role. If a different user logs in and does not own a particular blog, they s ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

javascript Click to add a tag

I am currently using a rich text editor and I'm attempting to add a code tag feature to it. Currently, the editor has two buttons - one for underline and one for code. When I select text and click the underline button, the selected text will be under ...

The upload method in flowjs is not defined

I am a novice when it comes to flow.js and am currently using the ng-flow implementation. I have a specific task in mind, but I'm unsure if it's feasible or not, and if it is possible, how to achieve it. I've created a factory that captures ...