簡體   English   中英

如何在AngularJS中動態創建表單元素?

[英]How to have dynamically created form elements in AngularJS?

我的觀點是:

  <div class="well well-sm" ng-repeat="item in receivingItems">
    {{ item.sku }}: {{ item.description }}<br />
    <form class="form-horizontal" role="form">
      <div class="form-group">
        <label class="col-sm-2 control-label">Quantity</label>
        <div class="col-sm-10">
          <input type="number" class="form-control" placeholder="">
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">Lot</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" placeholder="">
        </div>
      </div>
    </form>
  </div>
  <form class="form-inline" role="form">
    <div class="form-group">
      <label class="sr-only">SKU</label>
      <input type="text" ng-model="receivingValue" placeholder="SKU" typeahead="sku for sku in getSku($viewValue) | filter:$viewValue" typeahead-on-select="selectedSku()" class="form-control" autocomplete="off" autocapitalize="off">
    </div>
  </form>

在我的控制器中,我有:

  $scope.selectedSku = function() {
    var sku = $scope.receivingValue.split(':')[0];
    ItemService.getBySku(CompanyService.getCompany()._id, $scope.selectedClient._id, sku).then(function(response) {
      $scope.receivingItems.push(response.data.item);
      $scope.receivingValue = null;
    });
  }

所以這符合您的期望。 當您搜索SKU時,它將創建一個帶有“ 數量批次”字段的新表單。 但是現在,當我提交總體表單時,我希望以某種方式存儲和保存這些值。 那么,如何對動態字段元素使用ng-model (或不必?)?

由於您有這種方式,我建議您使用ng-form這樣,以便可以將表單封裝在表單中,並仍然使用Angular提供的驗證功能:

$scope.mySubmit = function(items) {
    myResource.ajaxProcessItems(items)
    .success(function(response) {
        //
    });
};

<div ng-form ng-submit="mySubmit(receivingItems)" name="myParentForm">
    <div class="well well-sm" ng-repeat="item in receivingItems">
        {{ item.sku }}: {{ item.description }}<br />
        <div ng-form class="form-horizontal" role="form" name="{{item.description}}">
          <div class="form-group">
            <label class="col-sm-2 control-label">Quantity</label>
            <div class="col-sm-10">
              <input type="number" 
                ng-model="item.sku"
                class="form-control"
                placeholder=""
                name="sku">
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-2 control-label">Lot</label>
            <div class="col-sm-10">
              <input type="text"
                class="form-control"
                placeholder=""
                ng-model="item.description"
                name="description" />
            </div>
          </div>
        </form>
    </div>
    <button type="submit">Submit</button>
</div>

暫無
暫無

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

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