2014-03-28 32 views
4

我有一個角度的應用程序,收集物品的價值發票,我要確保只有獨特的項目被添加到該集合,但我有沒有運氣。角 - 只推到數組,如果唯一

我推3條信息給這個集合:ID,價格和類型。我想確保目前收集的內容中沒有任何內容符合這3點。

// My container 
$scope.invoice = { 
    items: [{ 
    }] 
} 


    $scope.addPhoto = function() { 
    console.log('Withdrawing Photo: '+ $scope.item.id); 
    if ($scope.invoice.items.indexOf(item.id) != $scope.item.id) 
    { 
     $scope.invoice.items.push({ 
     id: $scope.item.id, 
     price: $scope.item.price, 
     type: 'photo' 
    }); 
    } 
} 

//試圖避免集合這樣

發票:{ 項目: [{},{ ID:25 價格:0 類型:相片 },{ ID: 25 價:0 類型:相片 }] }

enter image description here

回答

2

這是我想出瞭解決我的問題的解決方案,希望它可以幫助別人。

$scope.addPhoto = function() { 
    console.log('Withdrawing Photo: ' + $scope.item.id); 
    var newItemId = $scope.item.id; 
    var newItemPrice = $scope.item.price; 
    var newItemType = 'photo'; 
    var matches = true; 


    // Make sure user hasnt already added this item 
    angular.forEach($scope.invoice.items, function(item) { 
     if (newItemId === item.id && newItemPrice === item.price && newItemType === item.type) { 
      matches = false; 
      $scope.message = 'You have already selected to withdraw this item!'; 
     } 
    }); 

    // add item to collection 
    if (matches != false) { 
     $scope.invoice.items.push({ 
      id: $scope.item.id, 
      price: $scope.item.price, 
      type: 'photo' 
     }); 
     $scope.total += $scope.item.price; 
     $scope.message = 'Total Amount Selected'; 
    } 
}; 
7

.filter幾乎是你所需要的。

$scope.addPhoto = function() { 
    console.log('Withdrawing Photo: '+ $scope.item.id); 
    var matches = $scope.invoice.items.filter(function(datum) { 
     return datum.id === $scope.item.id && 
     datum.price === $scope.item.price && 
     datum.type === $scope.item.type; 
    }); 
    if (!matches.length) 
    { 
     $scope.invoice.items.push({ 
     id: $scope.item.id, 
     price: $scope.item.price, 
     type: 'photo' 
    }); 
    } 
} 

Semi-contrived JSFiddle

+0

Hmmmm它仍然讓我兩次(見上文)收集添加同一項目 – xXPhenom22Xx

+0

@ xXPhenom22Xx有我的回答一個錯字,請編輯和JSFiddle。 – SomeKittens

+0

它仍然讓我一遍又一遍地添加相同的記錄再次...:/ – xXPhenom22Xx

1

你可以把簡單的流行相對

array.splice(array.pop(item));