ng-repeat中的angularjs动态表单字段

时间:2016-08-31 11:38:56

标签: angularjs ng-repeat dynamicform

您好我在ng-repeat中添加表单字段和绑定有问题 我的表格是这样的

    <div ng-repeat="(key, value) in categories">

        <div class="col-sm-12"><b>{{ value.name }}</b></div>
            <div class="col-sm-12" >       
                <div class="col-sm-3">
                  <label>Product</label>
                  <input 
                   type="text" 
                   class="form-control input-sm" 
                   ng-model="product.name">
                 </div>

                 <div class="col-sm-1">
                    <label>&nbsp;</label>
                    <button type="button" ng-hide="$first" ng-click="removeProduct()">-</button>
                 </div>
            </div>

            <div class="col-sm-1">
                <button type="button" ng-click="addNewProduct()">+</button>
            </div> 
    </div>

json类别

[{"id":1,"name":"Furniture & Fixture"},
{"id":2,"name":"Miscellaneous Property"},
{"id":3,"name":"Office Equipment"},
{"id":4,"name":"Renovation"},
{"id":5,"name":"Vehicle"}]

在这里,我想为每个类别添加动态表单字段(产品)

我的js是这样的

$scope.addNewProduct = function(){

        $scope.categories.push({});
    }

$scope.removeProduct= function(index){
        $scope.categories.splice(index,1);
    }

我知道我不需要将数据推送到每个类别。请帮助

2 个答案:

答案 0 :(得分:1)

添加新类别的功能应如下所示:

$scope.addNewProduct = function(){
    var newCategory=
       {
          id:$scope.categories.length+1,
          name:$scope.product.name
       }

    $scope.categories.push(newCategory);
}

答案 1 :(得分:0)

以下代码将演示如何附加&#39; item&#39;到项目列表:

 <script>
      angular.module('AddItemToList', [])
        .controller('FormController', ['$scope', function($scope) {
          $scope.item = '';
          $scope.items = [];
          $scope.submit = function() {
            if (typeof($scope.item) != "undefined" && $scope.item != "") {

              // append item to items and reset item
              $scope.items.push($scope.item);
              $scope.item = '';
            }
          };
        }]);
    </script>
    <form ng-submit="submit()" ng-controller="FormController">
      Input item and Submit the form. This will get appended to the list:
      <input type="text" ng-model="input" name="item" />
      <input type="submit" id="submit" value="Submit" />
      <pre>Final List={{items}}</pre>
    </form>
相关问题