如何在AngularJS中动态创建表单元素?

时间:2014-03-11 21:55:38

标签: javascript angularjs angular-ngmodel

我的观点有:

  <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(或者我不必?)用于动态字段元素?

1 个答案:

答案 0 :(得分:1)

由于你的方式,我建议你像这样使用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>