xXPhenom22Xx xXPhenom22Xx - 6 months ago 31
AngularJS Question

Angular - Only push to array if unique

I have an Angular application that collects values of items for an invoice, I want to make sure only unique items are being added to this collection but am having no luck.

I am pushing 3 pieces of information to this collection: id, price, and type. I want to make sure there is nothing in the collection currently matching those 3 points.

// 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'
});
}
}


// Trying to avoid collections like this

invoice: {
items:
[ { } , {
id: 25
price: 0
type: photo
} , {
id: 25
price: 0
type: photo
} ]
}

enter image description here

Answer

This is the solution I came up with to solve my problem, hopefully it helps someone else.

    $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';
    }
};