Search code examples
angularjsangularjs-ng-repeatdynamicform

angularjs dynamic form field inside ng-repeat


Hi I have problem in adding form field and binding inside the ng-repeat
my form is like this

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

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

Here I want to add dynamic form fields(products) for each category

my js is like this

$scope.addNewProduct = function(){

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

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

i know its won't work i need to push data to each category.please help


Solution

  • Your function for adding new category should look like this:

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