簡體   English   中英

AngularJS在輸入字段中選擇選項

[英]AngularJS select options in an input field

我在AngularJS模板中有以下代碼:

<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>

我想為用戶提供以下選項的下拉菜單:

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

來自相應的組件文件。

我原本打算使用ui-select,但這似乎不是一個選項,因為我需要讓用戶能夠輸入不在選項列表中的數字。

除了要生成輸入框的"other"選項之外,您還需要結合使用HTML <select> (MDN)元素和AngularJS指令ngRepeat來創建列表中的選項( Codepen示例 ):

<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>

因此,在提交表單之前,您將需要檢查workoutHours的值是否等於'other' ,如果是,則提交綁定到workoutHoursOther的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM