Tips for creating a functional null option using the select ng-options feature

While there are a few questions and answers on this topic, I have yet to find a solution that works for my specific case.

Imagine having an object like this:

$scope.person = {name: 'Peter', category1: null, category2: null};

Another variable receives a list of categories through a $resource call with results like this:

$scope.categories = [{id:1, name:'Supplier'}, {id:2, name:'Customer'}];

It's simple enough to create a select dropdown using ng-options to choose from the available categories and set the selected category.id as person.category1 or person.category2.

However, the challenge lies in making category1 mandatory while allowing category2 to remain a valid null value.

Essentially, what I need now is two select dropdowns with the following options:

//Select1
- Select Category1 (disabled)
- Customer (value: 1)
- Supplier (value: 2)

//Select2
- Select Category2 (disabled)
- No Category (value: null)
- Customer (value: 1)
- Supplier (value: 2)

EDIT

I have added a Plunkr based on @Mistalis answer, demonstrating the desired outcome: Each select dropdown should have a disabled placeholder option, with one supporting a "valid null option".

Answer №1

To include a choice (blank) in your dropdown list, use the following code:

<select ng-model="categ.selected" ng-options="c.name for c in categories">
    <option value="">No category</option>
</select>

See Demo on Plunker


You can set categ.selected to null by default in your controller if necessary:

$scope.categ = {"selected": null};

Additional Info from Comment:

If you are unable to manually add 2 options in ng-options, consider adding the "No category" option within categories in your controller:

$scope.categories.push({id:null, name:'No category', noCat:'true'});

Note the noCat: 'true' which will be used to hide it from the initial dropdown list.

Your HTML code will now look like this:

<select ng-model="person.category1" 
        ng-options="c.id as c.name for c in categories | filter: {noCat: '!true'}">
    <option value="" disabled>Select Category 1</option>
</select>
<select ng-model="person.category2" ng-options="c.id as c.name for c in categories">
    <option value="" disabled>Select Category 2</option>
</select>

View New Plunker Example

Answer №2

When validating a form with Angular's form controller, be aware that empty values will not be considered valid. Instead, use the value (int)0.

  <select ng-model="person.category1" ng-options="category.id as category.name for category in categories | filter: {id: '!' + 0}" required>
    <option value="">Select Category 1</option>
  </select>
  <select placeholder="Select Category 2" ng-model="person.category2" ng-options="category.id as category.name for category in categories" required>
    <option value="">Select Category 2</option>
  </select>

To make the "Select Category" options unavailable to select at all, like a placeholder, add the disabled attribute to the <option>

For a demonstration, check out this jsfiddle link.

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

Visit a webpage on my site

Is it feasible to embed a website within another website? Suppose I have my index.html file. What if in the center of that file, we include an iFrame or similar element that loads , allowing users to explore Google directly on my website? ...

Can you explain the term 'outer' in the context of this prosemirror code?

Take a look at this line of code from prosemirror js: https://github.com/ProseMirror/prosemirror-state/blob/master/src/state.js#L122 applyTransaction(rootTr) { //... outer: for (;;) { What does the 'outer' label before the infinite loop ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Mongoose, Angular, and Express are not functioning properly when using the PUT method

I'm having trouble with implementing a basic edit function in my application. The delete and get functions are working fine, but I keep encountering a 500 error when trying to make a put request. I've attempted using findByIdAndUpdate and FindOne ...

What are some effective methods for handling error objects in REST API services?

Encountered an error object: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES) Type of (err): Object Now, I am looking to pass this object to another web service (REST API) What content ty ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

Responding with a 404 Error in Node.js and Express with Callbacks

Apologies for the lackluster title, I couldn't come up with anything better. Let's delve into the following code snippet: app.use(function(request, response){ request.addListener('end', function() { parseUrl(request.url, fu ...

How to dynamically alter a PHP variable using a JavaScript button click on the existing webpage

I've spent the last hour scouring stackoverflow for answers to my problem, but trying out solutions has only resulted in errors - perhaps because I'm attempting to implement it on the same page. I've experimented with saving the value to a ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

Using AngularJS ng-controller within an $http request is causing issues

I have an example of HTML code: <div ng-bind-html="model.main_container"></div> And I am executing something similar in AngularJS: $http.get("/submit", { cache: true }) .success(function(data, status) { if ( status == 200 ) { ...

Discover the method of obtaining the post id within an Ajax callback in the Wordpress

Currently, I am using the Add to cart Ajax callback, but I am facing difficulty in retrieving the post Id from it. MY OBJECTIVE: My intention is to apply the add_filter only on a specific page. Here is the PHP code in functions.php file: add_filter( &apos ...

What is the best way to continuously add items to a div until their heights are equal?

In my layout, I have two divs positioned next to each other. Typically, the left div displays n+2 items while the right div displays n items. The value of n changes depending on the category and is already set. However, there are instances where certain ...

Refreshing a section of a webpage using AJAX and PHP

After creating a RESTful API in PHP, I can easily register information by accessing the address . This registration process involves sending a POST request. Below is an overview of my method: File: api.php <?php /* File: api.php */ private function ...

Ways to troubleshoot and resolve the jQuery error with the message "TypeError: 'click' called"

I am currently developing a project for managing Minecraft servers, focusing on a configuration panel. I have set up a form that users need to fill out in order to configure the settings and send the values using Ajax. However, I encountered an error: Type ...

What is the process for integrating Internet Explorer 10 compatibility into a basic VueJs component?

I am facing an issue with a VueJs component that is not rendering in IE 10. Context: The Vue component I am working on is a company events list with basic filtering and sorting functionalities. Unfortunately, IE10 support is required for this project. Eve ...

A guide on combining two counters in Vue to create a unified value

Is there a way to track the number of times two buttons are clicked individually as well as together? <div id="app"> <p><button v-on:click="counter1 += 1">Add One More Click</button></p> <p>&l ...

Incorporate measurement markers into the graphic (ESRI JavaScript)

Is there a way to add a scale to a single graphic in a graphics layer? I currently have all the graphics shown in the same scale, but I need each graphic to have a different scale. I added the graphics using map.graphics.add() and SimpleSymbol. Any sugge ...

Iterate through an Array of Objects and exhibit a single object property in HTML one at a time by utilizing Javascript

I am working with an array of objects that contain two properties: "quote" and "author". I have a container div where I want the quotes to be displayed one by one at an interval of every 2 seconds. Currently, it is showing one letter at a time instead of d ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...