如何使用splice

时间:2017-05-04 04:29:48

标签: angularjs forms nested-forms splice

我有一个嵌套的表单....我可以添加新字段,但删除字段时遇到一些问题。

我希望能够拼接对象数组中的特定位置以删除字段

目前我有......

HTML:

<div ng-repeat="senarioItem in attendees.formData.scenarios[0].scenarioItems" class="row">
        <div ng-hide="cost._destroy">    
            <div class="form-group col-xs-5">
                <label for="costDescription">Description</label>
                <input class="form-control input-group-lg" type="text" name="costDescription" ng-model="senarioItem.costDescription"/>
            </div>
            <div class="form-group col-xs-2">
                <label for="cost">Amount</label>
                <input 
                    class="form-control input-group-lg" 
                    type="number" 
                    name="cost"
                    ng-model="senarioItem.cost"/>
            </div>

            <div class="col-md-2">
                <a ng-click="removeCost()" class="btn btn-xs btn-danger">X</a>
            </div>
        </div>
    </div>

控制器:

attendees.removeCost = function(){
            var cost = attendees.formData.scenarios[0].scenarioItems[index];
            if(cost.id) {
                cost._destroy = true;
            } else {
                attendees.cost.splice(index, 1);
            }


        var cost = attendees.formData.scenarios[0].scenarioItems[index];
    };

JSON:

"scenarioItems": [
        {
          "cost": "",
          "costDescription": "",
        },
        {
          "cost": "",
          "costDescription": ""
        },
        {
          "cost": "",
          "costDescription": ""
        },
        {
          "cost": "",
          "costDescription": ""
        }
      ]

1 个答案:

答案 0 :(得分:0)

将索引作为参数传递给函数

#populatedByAjax

然后在函数

中删除它
<div class="col-md-2">
   <a ng-click="removeCost($index)" class="btn btn-xs btn-danger">X</a>
</div>