issue with AngularJS model not initially binding to select dropdown

I am facing an issue with a select dropdown in my code. I am using ng-repeat to populate the dropdown like this:

<select ng-model="tstCtrl.model.value" required>
  <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
</select>

Once an option is selected, the binding to model.value works as expected. However, initially the selected dropdown option does not seem to be bound to the value that model.value is set to.

This issue can be seen in the example below:

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>

  <script>
    angular.module('Test', []).controller('TestController', function(){
      
      this.model = {
        value:3
      };
      
      this.myOptions = [
        {a:1, b:"one"},
        {a:2, b:"two"},
        {a:3, b:"three"},
        {a:4, b:"four"},
        {a:5, b:"five"}];
    });
  </script>
  </head>

  <body ng-app="Test" ng-controller="TestController as tstCtrl">

    {{tstCtrl.model.value}}

    <select ng-model="tstCtrl.model.value" required>
      <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
    </select>

  </body>



</html>

The provided snippet should clearly demonstrate the issue. Feel free to ask me any questions you may have.

Any suggestions on how to resolve this problem would be greatly appreciated!

Thank you!

Answer №1

It is recommended to utilize the ng-options syntax rather than using an ng-repeat within your select element. To display property b but bind to property a, you can implement the following syntax:

<select ng-model="model.value" ng-options="option.a as option.b for option in myOptions" required>      
</select>

Check out your updated and functional code snippet below:

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>

  <script>
    angular.module('Test', []).controller('TestController', function($scope){
      
      $scope.model = {
        value:3
      };
      
      $scope.myOptions = [
        {a:1, b:"one"},
        {a:2, b:"two"},
        {a:3, b:"three"},
        {a:4, b:"four"},
        {a:5, b:"five"}];
    });
  </script>
  </head>

  <body ng-app="Test" ng-controller="TestController">

    {{model.value}}

    <select ng-model="model.value" ng-options="option.a as option.b for option in myOptions"  required>      
    </select>

  </body>



</html>

Answer №2

If you find yourself in a situation where you need to utilize ng-repeat, one possible way to do so is outlined below:

    <select ng-model="tstCtrl.model.value">
      <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}" 
              ng-selected="tstCtrl.model.value==option.a">
                   {{option.b}}
       </option>
    </select>

However, it would be wise to heed the advice of others and opt for using ng-options instead.

Answer №3

When transitioning from AngularJS 1.3.x to 1.4, there is a known issue related to ng-model and select dropdowns. The Angular documentation has been updated with a recommended solution:

app.directive('convertToNumber', function() {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {                
            ngModel.$parsers.push(function(val) {                    
                return parseInt(val, 10);
            });
            ngModel.$formatters.push(function (val) {                    
                return '' + val;
            });
        }
    };
});

To implement this fix, simply add the directive to your select dropdown:

<select ng-model="tstCtrl.model.value" convert-to-number required>
  <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
</select>

You can find more information on this solution at the following URL:

Answer №4

To implement ng-options, you can use the following syntax instead of ng-repeat:

ng-options="opt.x as opt.y for opt in availableOptions"

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

Can you identify the distinctions between these two lines?

As a beginner in React, I recently learned how to create a timer counter following a tutorial. However, I am slightly confused about the difference between these two lines of code. Can someone please explain what is occurring in the first line below? lin ...

Twitter typeahead with a dynamic array of strings

Currently, I am making an ajax call to retrieve a list of objects. Once this array of objects is filled, a separate string[] is created with the names of these objects. My goal is to pass this data to Twitter Typeahead using a Bloodhound source. However, ...

Is there a way to retrieve a file received in a response to a POST request using nodejs?

I'm encountering an issue with sending a POST command to download a file. I am attempting to send a POST request with a specific URL from the client side, along with a parameter that indicates the file to be downloaded. var req = $.ajax({ type: ...

Learning to transform EST time data into local time within JavaScript utilizing moment.js and Date objects

The recorded date and time is "03/19/2020 13:15:00" in Eastern Standard Time (EST). When attempting to convert it to the local timezone, I have tried various methods, such as using moment.js to change the format from 'MM/DD/YYYY HH:mm:ss' to UT ...

The 'disable' prop in Material UI textfield fails to update after the initial change

Currently, I am working on a program that involves radio switches, each representing a different boolean value. This program aims to toggle the 'disable' property of a textfield based on the boolean value selected by the user. The issue I am faci ...

Exploring the KEY attributes within a JSON dataset

In my React project, I am working on displaying specific key values from a JSON response. For example, the fieldData {DMR_5_why_who_test: "test", why: test}. My goal is to only show the bolded or key values in my output. However, my current code is not a ...

In order to use DIV jQuery, it is necessary to have at least one input

In my form, there are 5 input fields. On button click using JQuery, I need to validate that at least one of these inputs is filled out. <div id='myForm'> <input name="baz" type="text" /> <input name="bat" type="text" /> ...

Is it possible to implement Ajax functionality in JavaScript without using XMLhttp and connection the same socket for every request?

Can data on a page be communicated and updated without the need for reloading, all while avoiding the XMLHttpRequest object and using the same connection or socket for each request (without closing the connection each time)? ...

What may be causing a configuration problem with the USB binding in Electron?

I am encountering difficulties with installing USB modules in my electron app. Every time I attempt to install electron and its dependencies, I encounter the issues outlined below. Can someone please assist me in resolving this? If anyone has faced a simi ...

Using Three.js BVHLoader in React/React Native applications

I am currently working on developing an application or website for displaying BVH animation. I came across a BVHLoader example in Three.js that I found interesting: BVHLoader example. I am aware that React and React Native can be used with Three.js as we ...

The issue of Angular curly braces malfunctioning in some simple code examples reversed my

<head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script> </head> <body style="padding: 20px 20pc;"> <div ng-app="app"> ...

The full screen menu is exclusively displayed in the navigation bar

My HTML and CSS code is causing an issue where the full-screen menu only appears in the nav bar. This problem seems to be specific to Safari. To solve the issue, I need to remove the following code: .nav { position: fixed; } However, I still ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

dependency in useEffect hook not being properly updated

Currently, I am implementing an API call within the useEffect hook in the following manner: useEffect(() => { fetchPatientsStartAsync(patientListUrl); }, [patientListUrl]); Moreover, in my codebase I have two additional state variables and a method in ...

Bidirectional Communication between ExpressJS and Mongoose Models

Let's consider a scenario where we have a User model and a Book model in our express app, both referencing each other. How can mongoose middleware be utilized to ensure that both models stay synchronized when saving either one? It would be beneficial ...

Error in setting cookies using Javascript document.cookie on iOS with cordova-plugin-ionic-webview

Backend-sent cookies are successfully stored, but the app itself cannot set cookies. When running the code snippet below: document.cookie = "notified=1; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"; console.log(document.cookie); An empty strin ...

Utilizing jQuery UI Slider for Calculating Percentage

I recently worked on an example where I incorporated 5 sliders, which you can see here: Example: http://jsfiddle.net/redsunsoft/caPAb/2/ My Example: http://jsfiddle.net/9azJG/ var sliders = $("#sliders .slider"); var availableTotal = 100; ...

Console does not display AJAX response

Currently, I am utilizing AJAX to fetch form data from a Django application and my objective is to display the response in the console. $.ajax({ type: 'GET' , url: url, data: {'PUITS': PUITS ...

AngularJS can retrieve the selected value from a select tag

<select ng-model="data.person"> <option value="1" selected="">1 pax</option> <option value="2">2 pax</option> </select> The ng-model above returned "1 pax," but how can I retrieve ...

Exploring the connections between Hibernate and AngularJS

I have established a connection between Travelers and Trips in Hibernate: https://i.sstatic.net/YQetP.png To create a new trip for traveler 1, I need to visit the route /frontend/#/trip-creation/1. Here, a form is available: https://i.sstatic.net/BeXnU. ...