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