AngularJS: How to eliminate empty select options in ng-repeat using Angular framework

My code is utilizing ng-repeat to display options with different values and texts, while also designating a default selection. However, Angular is introducing an additional empty undefined option.

<select ng-model="newItem.financial_year_id" required style="min-width:180px;">
   <option ng-repeat="financial in account_year" value="{{financial.id}}" ng-selected="financial.status=='Active'">{{financial.financial_year}}</option>
</select>

Although the active option is correctly selected, an unwanted empty option continues to appear.

Answer №1

When using ng-model with ng-options, an empty option can be generated if the value referenced by ng-model is not present in the set of options provided.

You can refer to a comprehensive answer and example on stackoverflow by following this link

UPDATE:

Here's a demonstration:

 <select ng-model="newItem.financial_year_id" required style="min-width:180px;">
   <option ng-repeat="financial in account_year" value="{{financial.id}}" ng-selected="financial.status=='Active'">{{financial.financial_year}}</option>
</select>

In the controller:

$scope.newItem={};
$scope.account_year=[{id:1,financial_year:"2013-2014",status:"Active"},
                     {id:2,financial_year:"2014-2015",status:"Inactive"}] 
//remove empty option
$scope.newItem.financial_year_id=$scope.account_year[0].id;

Check out the live example: http://jsfiddle.net/choroshin/5YDJW/7/

Answer №2

Consider using ng-options instead:

<select ng-model="selectedFinancial" ng-options="c.financial_year for c in account_year"
        required style="min-width:180px;">
</select>

DEMO

Your data model could benefit from utilizing ng-options. When using <select>, ensure there is only one selected item which should be a property of $scope referring to an item in the list, eliminating the need for additional properties like "active" and "inactive" for each object.

The current model design is suitable for multiple selected items, otherwise consider using checkboxes rather than <select>

To bind with Id, you can try this approach:

<select ng-model="selectedFinancialId" ng-options="c.id as c.financial_year for c in account_year"
        required style="min-width:180px;">
</select>

DEMO

Answer №3

When it comes to handling options in Angular, ng-option is a great choice. However, if you prefer using ng-repeat, make sure to follow this syntax:

$scope.newItem.financial_year_id = "";

It's important to initialize the variable at the start of the controller. Failure to do so may result in the variable being undefined, leading to an initial empty 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

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

What is the best way to transfer static assets from an npm package to a nuxt project?

Has anyone successfully sent assets from an npm package to a nuxt application before? I have a vue component within an npm package with the following structure: -src/ -assets/ -noun-filter.svg In this npm package, the vector image is included in the v ...

Prevent submission of form by disabling button until modifications are made to the original data in Vue.js

For experimental purposes, I have created a simple form and am trying to implement a feature where the button remains disabled until the original form data is changed. Additionally, I want to ensure that the button stays disabled even if the changed data i ...

Creating keyboard navigation for an HTML ul list: A step-by-step guide

What is the best way to enable list navigation using keyboard arrows for an HTML ul list? ...

Angular ForkJoin() Problem Encountered

Hello, I am currently designing a User Interface and I need to display a unique JSON response value for each 'digId'. In the example below, there are 3 incidents and I used forkJoin to access the 3 JSON responses. digId='4149'; ...

Validating user input fields to display error messages when empty

As part of my program, I need to gather information from users regarding their name and the number of pets they have. If a user enters an empty string, I want to display an error message prompting them to input something and fill the text box with their en ...

ng-view not functioning as it should

Hey there! I attempted to create a simple plunkr to explore loading times in SPAs with ng-view, but it looks like I can't even get a valid scenario up and running. My goal is to have a SPA with a ng-view and 2 templates. Each template should display ...

Having difficulty transferring a JSON object's property to a different variable

I'm currently creating a Weather App project for FreeCodeCamp and you can check out my progress on CodePen. To fetch my current location data, I'm utilizing this API. However, I've encountered an issue when trying to assign object propertie ...

The error message "Create controller with service — Get... is not a function" indicates that

Within my ASP.NET Boilerplate project, the following code snippet is present: (function () { appModule.controller('augustinum.views.kostenstelle.index', [ '$scope', '$uibModal', 'abp.services.app.kostenstelle ...

Ways to store debug logs in a file within my project

In the project I am currently working on, I incorporate the Debug package which can be found at https://www.npmjs.com/package/debug. As part of this setup, I have set an environment variable (variable name: DEBUG & value:*). As a result, I am able to vie ...

Best practices for starting and stopping trace spans in express / nodejs applications

Currently, I am conducting an experiment with utilizing the Opentelemetry.js nodejs/express library and attempting to refactor the reviews application from the bookinfo Example found in Istio. I followed the tracer configurations laid out in the sample: ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

Whenever I use Vue JS, instead of receiving my array of objects, I am returned with [__ob__: Observer

Struggling to retrieve data from the database using an API call in my VueJS application. I'm new to VueJS and JavaScript, tested the API with Postman and received the correct JSON response. Current output: [__ob__: Observer] length: 0 __ob__: Observ ...

Incompatibility in Parse Cloud Code syntax leading to query failure

We are in need of an aggregation pipeline that utilizes various stages like: addFields, lookup, group, and unwind. However, there seems to be a discrepancy when converting the MongoDB Compass syntax into Parse Cloud Code JavaScript calls, as we are not ach ...

AngularJS offers a helpful solution for exchanging data across controllers by utilizing the $broadcast method

I've been struggling with utilizing $broadcast and $on functions to transfer data between two controllers. On my main webpage, there is a button that increments a variable by 4 each time it's clicked: <!DOCTYPE html> <html xmlns="http: ...

Bringing in Node Package in Angular

I decided to clone the Angular project from here: https://github.com/etherparty/explorer Now, I am looking to incorporate another module into it by following this link: https://github.com/miguelmota/ethereum-input-data-decoder However, when trying to uti ...

I am puzzled as to why my Details Modal keeps appearing whenever I click anywhere, even when I have specifically added it to only show up on the event of today. Additionally, I am encountering

ERROR Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref at coerceRef (http://localhost:3000/static/js/bundle.js:59386:21) at createChil ...

Can Angular 5 integrate with Pusher?

Below is the javascript code used to integrate Pusher into native HTML: <head> <title>Pusher Test</title> <script src="https://js.pusher.com/4.1/pusher.min.js"></script> <script> // Enable pusher logging - don't i ...

What are the common practices for UI bindings in JavaScript and AJAX applications?

Background Information Currently, I am in the process of developing a traditional web application with most forms operating through AJAX. I am facing challenges in connecting the user interface to the model. As of now, I have to explicitly: Specify the ...

Move files into the designated folder and bundle them together before publishing

Is there a way to transfer the files listed in package.json (under the File field) to a specific folder in order to bundle them together with npm publish? Here is the structure of my repository: . ├── package.json └── folder0 ├── fil ...