Selecting options in an input field using AngularJS

In my AngularJS template, I have the code snippet below:

<input
    type="number"
    id="exercise-log-duration-hours-{{ ::$id }}"
    class="form-control"
    ng-model="$ctrl.workoutHours"
    ng-change="$ctrl.updateHours($ctrl.workoutHours)"
    name="{{ ::$ctrl.inputName }}"
    step="1"
    min="1"
    required> 
  </input>

I am looking to provide users with a dropdown selection of options:

ctrl.hourOptions = [1, 2, 3, 4, 5, 6];

This is defined in the corresponding component file.

Initially, I planned to use ui-select for this purpose. However, after considering the user's need to input custom values not included in the dropdown list, this approach seems impractical.

Answer №1

To create a dropdown menu with options in HTML, you can use the <select> element (MDN), combined with the AngularJS directive ngRepeat. This will allow you to generate the list of options from a predefined array and include an additional "other" option that triggers an input box (Codepen example):

<div ng-app="example" ng-controller="ExampleController as $ctrl">
  <select id="exercise-log-duration-hours-{{ ::$id }}"
          class="form-control"
          ng-model="$ctrl.workoutHours">
    <option value="other">Other</option>
    <option ng-repeat="hour in $ctrl.hourOptions" value="{{hour}}">{{hour}}</option>
  </select>
  <div ng-if="$ctrl.workoutHours === 'other'">
    <input type="number" min="1" step="1" ng-model="$ctrl.workoutHoursOther" />
  </div>
  <p>Selected: {{$ctrl.workoutHours}}</p>
</div>

Prior to submitting your form, make sure to validate if the selected value in workoutHours is equal to 'other'. If it is, submit the data stored in workoutHoursOther instead.

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

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...

What is the best way to achieve this particular grid layout using html and css?

I have a CSS grid of icons and I am trying to create a divider between each cell that fades in opacity towards the edges, similar to an airbrush effect. However, I want the cells themselves to remain transparent so that the background pattern is still visi ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

Tips for transferring information from the isolate scope to the parent scope

As a newcomer to AngularJS, I am exploring the creation of directives and how to invoke functions from the parent scope within them. While I have successfully achieved this, I am now grappling with the challenge of passing data from the isolate scope via a ...

What is the process for including a new dependency in Angular module's dependency array?

I am attempting to utilize the angular-bootstrap-nav-tree library in my project, but I am encountering an issue where I cannot add 'angularBootstrapNavTree' to the list of dependencies for my module. The error message I am receiving is "Unknown p ...

The Node.js application gracefully exited with code 0 with Forever

Running a Node.js Express app on CentOs 6.5 using the root account: root@vps [/home/test/node]# npm start app.js > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaee9e809e809f">[email protected]</a> s ...

Exploring how Node.js, Express.js, and Mongoose work together to handle

I am experiencing difficulties with handling data received from APIs, as it returns null and doesn't wait even though I have used async/await functions. My goal is to retrieve data from the first URL, then gather data from other URLs based on the res ...

Developed a hierarchical JSON format using a JavaScript array

I am aiming to generate a properly structured nested JSON file from an array, with unique key values. Currently, I can only output the JSON without any nesting. The desired structure to be displayed in the console is : { "Key" : "data1", "header" ...

Is the new Angular 2 CLI tool incorporating Systemjs?

Seeking Answers Curious about the absence of systemjs.config.js file when using the new Angular2 CLI setup tool. Is there a way to install a basic version of Angular 2 without relying on the CLI tool available on angular.io? Past Experience In the past, ...

What are the steps to include JSON data in my Angular page using ng-include?

When I run app.html, my JSON loads successfully. However, when I try to run projects.html from another directory, the JSON file does not load. Can someone help me figure out what I'm doing wrong? SITE STRUCTURE: **SITE** app/ app.html todo ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Issue with AngularJS: Copying and appending with $compile is not functioning properly

Below is the snippet of my angularjs Controller var $tr = angular.element("#parent" + obj.field_id).find("tbody"), $nlast = $tr.find("tr:last"), $clone = angular.copy($nlast); $clone.find(':text').val('' ...

AngularJS is throwing an error because it is unable to access the property `$valid` on an undefined object

I am currently working on a web application using AngularJS and I have created the following form: <form name="form2" novalidate><multiselect class="input-xlarge" multiple="true" ng-model="selectedCar" options="c.name for c in cars" change="selec ...

Receive AJAX aid for PHP/MySQL dynamic dropdown menu implementation

My goal is to dynamically populate a second drop-down menu based on the selection made in the first drop-down. The first drop-down contains a list of tables from my database, and the second drop-down should display providers associated with the selected ta ...

When would this be required within JavaScript or Angular?

Being new to JavaScript, I have come across information stating that the value of this changes based on how a function is invoked. However, I am confused about when it is necessary to use this and when it is not. Some code examples I've seen utilize t ...

Top method to create a timer in React/Redux for automatically refreshing authentication tokens

I am implementing an access refresh jwt authentication flow and need the client to automatically send a refresh token after 10 minutes of receiving the access token. I also want to ensure that if the user's device is idle for an hour, a new access tok ...

Ignore the initial element when iterating in ng-repeat

I need help excluding the first item in ng-repeat ..first item here <ul class="highlight-topright"> <li ng-repeat="item in hpHeadlines | filter:$index>0"> ... </li> </ul> Why isn't the filter ...