簡體   English   中英

我想避免 id 重復並使用 push 添加值

[英]I want to avoid id duplication and add values using push

控制器
$scope.items = [
{"id" : 1 , "itemname" : "name_1", "comment" : "dsdsd", "price" : 5000},
{"id": 1, "itemname": "name_2", "comment": "dddd", "price": 3000},
{"id" : 3 , "itemname" : "name_3", "comment" : "sdasd", "price" : 2000},
{"id" : 4 , "itemname" : "name_4", "comment" : "asdasd", "price" : 3000},
{"id" : 5 , "itemname" : "name_5", "comment" : "asdasd", "price" : 2000}
]

$scope.addToCart=function(item){
購物車。添加(項目);
}

服務
carObj.cart.add=function(item){
carObj.cart.push(item);
};

<div ng-repeat="item in cart">
<div>id: {{item.id}}</div>
<div>itemname: {{item.itemname}}</div>
</div>

頂部代碼cart.html

<div ng-repeat="item in items">
<a ng-click="addToCart(item)">[ addcart ]</a>
</div>

頂部代碼 index.html

示例輸出
編號 1
名稱_1 5000
name_2 3000
編號 3
name_3 2000
編號 4
name_4 3000
編號 5
name_5 2000

在推送到數組之前,您可以檢查推送到數組是否安全。

if ($scope.items.indexOf(item) == -1) {
   $scope.items.push(item);
}

在推送之前,您可以檢查是否已經存在具有該 ID 的項目。

let oldItem = $scope.items.find(elm => elm.id === item.id);
if(oldItem){
    //you can assign the properties of `item` to the one in the list
    Object.assign(oldItem, item);
}else{
    $scope.items.push(item);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM