My javascript/angular code is performing contrary to what i expect and i can't figure out why. I have an angular service defining two methods for getting and setting items
app.factory('orderItems',['Restangular','$mdDialog',function(Restangular,$mdDialog){
var orderItems = [];
return{
getOrderItems: function(){
return orderItems
},
setOrderItems: function(item,fillings){
...
orderItems.push(item)
...
}, ...
Items are set using ng-click
and passing an item and checked addons;
product_template.html
<div >
<md-button class="md-raised" ng-click="showAddons($event,product)">Add to Cart</md-button>
</div>
controller
app.controller('productCtrl',['$scope','getProducts','orderItems','Restangular','$mdDialog',function($scope,getProducts,orderItems,Restangular,$mdDialog){
//$scope.products;
$scope.products = getProducts(Restangular);
// Dialog
$scope.showAddons=function(ev,product){
$mdDialog.show({
locals:{current_Product: product,},
//inline controller
controller:['$scope','current_Product','orderItems',function($scope,current_Product,orderItems){
$scope.product = current_Product;
$scope.addons = {
checked:[],}
...
}],
templateUrl: 'dialog.html',
targetEvent: ev,
})
}
}])
dialog.html
<md-list-item ng-repeat="addon in product.productAddons">
...
<md-checkbox class="md-secondary" checklist-model="addons.checked" checklist-value="addon"></md-checkbox>
</md-list-item>
<md-button class="md-raised" style="background-color:#f44336; color:#fff" ng-click="setOrderItems(product,addons.checked)">Done</md-button>
The problem arises when setOrderItems
is passed a similar object more than once. The first time around, orderItems.push works as expected then when a similar product is passed to 'setOrderItems', it is pushed to 'orderItems' but all items in 'orderItems' are updated to this currently set item.
That is, if orderItems
was[{name:"chicken burrito",fillings:[{name:"cabbage"},{name:"cheese"}],...}]
before, after setting a similar item but with diff fillings, orderItems
is updated to [{name:"chicken burrito",filling:[{name:"guac"}],...},{name:"chicken burrito",filling:[{name:"guac"}],...}]
. If setOrderItems
is passed a different product say [{name:"goat burrito",...}]
it is added as expected.
Can't happen to find a similar issue around. What am i doing wrong. I want to be able to add similar items but with different fillings to orderItems
.