Reputation: 2176
I have this array of objects here:
$scope.breadsticks = [
{
name: 'Garlic Buttered',
price: { priceSM: 3.99, priceMD: 4.99, priceLG: 5.99 },
size: { sizeSM: '6 pcs', sizeMD: '10 pcs', priceLG: '14 pcs' },
description: 'Garlic buttery goodness on a stick of cheesy bread.',
},
{
name: 'Mozzarella Stuffed',
price: { priceSM: 4.49, priceMD: 5.49, priceLG: 6.49 },
size: { sizeSM: '6 pcs', sizeMD: '10 pcs', priceLG: '14 pcs' },
description: 'Jam packed with that mozzarella gucci we know you love.',
}
];
I want to create a select list that only displays the size: { sizeSM: '6 pcs', sizeMD: '10 pcs', priceLG: '14 pcs' }
information:
<td>
<select ng-model="breadstick.selectedItem" ng-options="breadstick.size for breadstick in breadsticks">
</select>
</td>
<td>
{{breadstick.selectedItem.price}}
</td>
And I would also like the corresponding price to be displayed when the select list changes.
Any help or bumps into the right direction would be greatly appreciated.
Upvotes: 0
Views: 31
Reputation: 104775
Use the ngRepeat
object syntax:
<td>
<select ng-model="breadstick.selectedItem" ng-options="size as text for (size, text) in breadstick.size">
</select>
</td>
Demo: https://jsfiddle.net/vn2ppwp9/1/
Edit: If you want to get the price for the selected item size, it'd be easier to reformat the data like so:
$scope.breadsticks = [
{
name: 'Garlic Buttered',
price: [
{
size: "small",
price: 3.99
}, {
size: "medium",
price: 4.99
}, {
size: "large",
price: 5.99
}
],
size: [{
size: "small",
text: '6 pcs'
}, {
size: "medium",
text: '10 pcs',
}, {
size: "large",
text: '14 pcs'
}],
description: 'Garlic buttery goodness on a stick of cheesy bread.',
},
{
name: 'Mozzarella Stuffed',
price: [
{
size: "small",
price: 4.49
}, {
size: "medium",
price: 5.49
}, {
size: "large",
price: 6.49
}
],
size: [{
size: "small",
text: '6 pcs'
}, {
size: "medium",
text: '10 pcs',
}, {
size: "large",
text: '14 pcs'
}],
description: 'Jam packed with that mozzarella gucci we know you love.',
}
];
Now you can update the view repeat as:
<select ng-change="getPrice(breadstick, breadstick.selectedItem.size)" ng-model="breadstick.selectedItem.size" ng-options="size.size as size.text for size in breadstick.size">
</select>
Where the getPrice
function:
$scope.getPrice = function(breadstick, size) {
for (var i = 0; i < breadstick.price.length; i++) {
if (breadstick.price[i].size == size) {
breadstick.selectedItem.price = breadstick.price[i].price;
break;
}
}
}
Upvotes: 1
Reputation: 511
Use json filter:
<select ng-model="breadstick.selectedItem" ng-options="breadstick.size as (breadstick.size | json) for breadstick in breadsticks">
</select>
Upvotes: 0