javascript - 使用 Angular 或 js 从 json 对象中删除行

标签 javascript angularjs json

我的页面上有这个漂亮的小列表,您可以在其中按“+”添加新行(通过推送很容易)并删除带有“X”的行,我不知道该怎么做。

enter image description here

我的 JSON 结构:

 "priceExtra" : [
    {
        "price" : NumberInt(2330), 
        "calc" : "1 x 2330", 
        "name" : "Foo price"
    }, 
    {
        "price" : NumberInt(5000), 
        "calc" : "2 x 2500", 
        "name" : "Baa price"
    } 
    {
        "price" : NumberInt(300), 
        "calc" : "1 x ฿300", 
        "name" : "Check-out full Cleaning"
    }
]

我的代码:

//
// Add extra line
//
vm.addLine = () => {    
    vm.priceExtra.push(
        {
            name  : "", 
            calc  : "", 
            price : 0
        }
    ) 
}

//
// Remove line
//
vm.delLine = () => {    

}

问题是我在 priceExtra 数组中实际上没有任何唯一的键,甚至“价格”也可能在多行中重复。

我怎样才能做到这一点?

哦忘了添加 HTML

<tr style="height:38px;" ng-repeat="extraLine in vm.priceExtra">
    <td class="book-mid" style="width:50%;" colspan="2">
        <input type="text" ng-model="extraLine.name" id="lineName" class="book-field book-field-slim ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" data-ng-change="vm.changeRent()">
    </td>
    <td class="book-mid-right" style="width:30%;">
        <input type="text" ng-model="extraLine.calc" id="lineCalc" class="book-field book-right book-field-slim ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" data-ng-change="vm.changeRent()">
    </td>
    <td class="book-mid-right" style="width:15%;">
        <input type="text" ng-model="extraLine.price" id="lineprice" class="book-field book-right ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" data-ng-change="vm.changeTotal()">
    </td>
    <td style="width:5%; text-align:right; padding-left:4px;">
        <button class="book-button book-text-button col-std-gray" ng-click="vm.newTenant=false">
            <md-icon class="material-icons book-material" aria-label="Close">close</md-icon>
        </button>
    </td>
</tr>

最佳答案

使用 $index 获取 ng-repeat 中的索引:

...
<td style="width:5%; text-align:right; padding-left:4px;">
    <button class="book-button book-text-button col-std-gray" ng-click="vm.newTenant=false; vm.delLine($index);">
        <md-icon class="material-icons book-material" aria-label="Close">close</md-icon>
    </button>
</td>
...

并使用这个:

vm.delLine = (index) => {    
    vm.priceExtra.splice(index,1);
}

关于javascript - 使用 Angular 或 js 从 json 对象中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258139/

相关文章:

javascript - 5 秒后 Jquery 显示按钮

javascript - 通过 AJAX 使用 PHP 发送表单,无需刷新页面

angularjs - 奇怪的 Angular 异常 : [$rootScope:inprog] null already in progress

javascript - 如何让浏览器在单击按钮时导航到指定选项卡?

JSON.stringify 与序列化

Javascript 从平面对象创建嵌套对象

javascript - 从网站打开新的 Outlook,mailTo 链接太长,*.eml 文件 bcc 字段未加载

javascript - 如何通过 Angular 中的ng-style范围添加部分css属性值

javascript - 如何将 Google PageSpeed Insight JSON 结果转换为 HTML

javascript - jQuery Cookie 没有像它应该的那样在每次点击时设置