enhancing feature to enable automatic selection of chosen option

I am facing an issue with a dropdown that utilizes ng-options in Angular. There is a default option selected with an empty value, indicated by the "selected" attribute and matching the model's value.

Whenever I add a new element to the ng-options list, even if it does not have an empty value, it automatically becomes selected if the model still has an empty value (which points to the default empty option). The model's value remains empty, but the dropdown displays the newly added option as selected. I even tried setting the default option value to " " instead of just "", but the behavior stays the same.

Is there a way to prevent newly added options from being automatically selected?

<select class="form-control section" ng-model="action.prop">
            <option value="" disabled selected>Select Property</option>
            <option ng-repeat="prop in tr.props| orderBy:prop.name"
            value="{{prop.name}}"> {{prop.name}} </option>
</select>

Answer №1

Give this code a try:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">

        <select ng-model="selectedName" ng-options="x for x in names">

        </select>

        <p>{{selectedName}}</p>

        <button ng-click="add()">Add</button>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
            $scope.names = [""];
            $scope.selectedName = $scope.names[0]
            $scope.add = function() {
                $scope.names.push("new");
            }

        });
    </script>


</body>

</html>

Answer №2

Before initiating your dropdown function, ensure to assign a default value to your ng-model in the controller as shown below. This will make sure that it is always set to a predefined value.

Controller

$scope.selectOption = {};
$scope.selectOption.value = '';

Answer №3

While both Roth's and Nishant's solutions seemed viable for my issue, I ultimately decided to go with a different approach. Instead of using ng-options and a filter, I opted for an ng-repeat with a condition "ng-if="prop.name != ''". This was necessary because I noticed that there was a brief moment where the latest property with an empty name would show up in the ng-repeat loop, causing issues with setting it as selected due to ng-model being empty.

<select class="form-control section" ng-model="action.prop">
        <option value="" disabled selected>Select Property</option>
        <option ng-if="prop.name != ''" ng-repeat="prop in tr.props| orderBy:prop.name"
        value="{{prop.name}}"> {{prop.name}} </option>
</select>

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

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

Update geographic coordinates using Javascript

I am currently developing a Google Maps feature in a Rails 3.2.12 project. My goal is to update the Latitude and Longitude values through the infoWindow for the location created. When a user clicks on a marker on the map, an infoWindow will open displayin ...

Modifying button text dynamically during save operation with AngularJS

Is it possible to dynamically change the text on a submit button while data is being saved in a form? Here's an example of the button: <button ng-click="save()">Save data</button> I have updated my save function based on some suggestion ...

Sending an HTTP POST request from Angular 4 to Java SpringMVC results in the issue of POST parameters not

Currently, I am developing a REST API using Java Maven Spring Boot and Spring MVC. I have encountered an issue where Angular POST request parameters are not being recognized by SpringMVC's @RequestParam. Below is the Angular code snippet; saveAsSit ...

Incorporating a CSS stylesheet into the theme settings of the Stratus 2 Beta platform

I have been attempting to personalize my Stratus 2 Beta by implementing a custom theme. I created a separate CSS file named "stratus.css" and stored it in the CSS directory of my website - with the CSS code being identical to this example. Below is my Jav ...

Is there a way to track and monitor the ngRoute requests that are being made?

I am in the process of transferring a fairly large Angular 1.6 application from an old build system to Yarn/Webpack. Our routing is based on ngRoute with a complex promise chain. While sorting out the imports and dependencies, I keep encountering this err ...

What is the best way to append a single class while also ensuring any previously added classes are removed?

How can I apply the selected class and remove any previously selected classes? <html> <select name="Button-Style" id="Button-Style" style="width:100%;"> <option value="Sun-Flower">Sun Flower</option> <option value ...

Tips on creating Twitter Bootstrap tooltips with multiple lines:

I have been using the function below to generate text for Bootstrap's tooltip plugin. Why is it that multiline tooltips only work with <br> and not \n? I would prefer to avoid having any HTML in my links' title attributes. Current Sol ...

Transforming JSON data into HTML displays only the final <li> element

Please take a moment to review the question provided at the end of this post. I am struggling with understanding why only the last li element from the JSON is being rendered. As a newcomer in this field, any help or guidance would be greatly appreciated! ...

Retrieve text excluding a specific class or id using jQuery

I need help with extracting text from an HTML div. <div id="example"> I am writing a <span class='outer'>query for help <span class='inner'>on a coding forum</span></span> </div> const te ...

Saving the Auth0 user object in React Context for Typescript in a Next.js environment

I am working on integrating Auth0 user authentication into my React application using the useUser hook and the context API. My goal is to access the user object globally throughout the app by storing it in the userContext.tsx file: import { createContext, ...

Automated form with built-in calculations

Whenever a product is selected from the dropdown menu, the price value should be automatically filled in the input field with ID #price. Then, the user can enter the quantity in the input field with ID #quantity, and the total sum of price multiplied by qu ...

Animate the sliding effect without being limited to a specific list

In many ng-animate slide demonstrations, a predefined list of items is used for sliding transitions. But in my scenario, I am obtaining the next item through an ajax call and do not have a pre-defined list. What approach should I take to achieve a slide ...

"Encountering a Syntax Error When Using request.post in Dojo Framework on Button Click

Here are three questions to consider: 1) What strategies can be utilized to streamline this code and reduce nesting and quote-related complications? 2) Are there any suggestions for addressing the parsing error mentioned below? I've already tested sep ...

Creating an array like this in JavaScript during an API call using Ajax

"WorkingHours": { "Monday" : { "open" : "10:00 am", "close" :"5:00 pm" }, "Wednesday" : { "open" : "10:00 am", "close" :"5:00 pm" ...

Failed to locate lodash during npm installation

I recently set up my project by installing lodash and a few other libraries using npm: npm install grunt-contrib-jshint --save-dev npm install grunt-contrib-testem --save-dev npm install sinon --save-dev npm install -g phantomjs npm install lodash --save ...

howler.js resumes playing sprite sound after being paused

I have been working on setting up an audio sprite using Howler.js. The basic functionality of the sprite is working well, but I am facing an issue when trying to resume playback after pausing a sprite. When I call play(), it does not work as expected. sou ...

Tips on displaying the appropriate object value in a text field based on the selection from a dropdown menu

In my Ruby on Rails form, I have a dropdown menu with various category names: <td> <div class="div1"> <%= f.collection_select(:category_id, Category.all, :name, id: 'category_select', :include_blank => & ...

When attempting to initiate a new session, Webdriver.io receives an HTML response from selenium

Currently, I am attempting to execute my selenium tests using webdriver.io. However, the test runner is encountering failure when attempting to establish a session: [18:12:36] COMMAND POST "/session" [18:12:36] DATA {"desiredCapab ...

Function is never called by SetTimeout

Attempting to simulate a long running operation using a loop, like this: var x, y; x = true; y = false; while (x) { if (!y) { setTimeout(function() => { x = false; }, 1000); y = true; } } Wondering why the l ...