Question: How do I use the selected sizes as an index to match and show the correct price and tsin associated with that size index?
Notice:
I am attempting to create a connection between sizes, prices, and tsin
"Black": { "sizes": "X Small, Small", "prices": '$22.24, $24.94', "tsin": "111002, 111003" },
For example, if black is chosen and the size selected is index [0] (or X Small), then when ng-change occurs, the price should update to $22.24 and the tsin should be 111002
UPDATE: I have made some modifications in an attempt to reach the desired functionality but prototypical inheritance is still missing. Just aiming to demonstrate the intended effect
UPDATED 2x Received a solution from Callebe which brought me closer, yet still not fully functional
JSFiddle
I have a basic controller with some mock data fetched via $http:
var app = angular.module("app", []);
app.controller('Ctrl', function ($scope, $filter, $http) {
//lowest price is fetched during the initial API request on production
var lowestPrice = '$21.24';
// exposes currentPrice to the view
$scope.currentPrice = lowestPrice;
// function to switch the currentPrice to the price of the selected product
$scope.getCurrentPrice = function(idx) {
$scope.currentPrice = idx;
}
//mock data simulating part of the json object response
$scope.productData = {
"colors_and_sizes": {
"data": {
"Black": {
"prices": '$21.24, $29.94',
"swatch_image": 'http://lorempixel.com/50/50',
"sizes": "X Small, Small",
"prices": '$22.24, $24.94',
"tsin": "111002, 111003"
},
"Blue": {
"swatch_image": 'http://lorempixel.com/50/51',
"sizes": "X Small, Small",
"prices": '$22.24, $24.94',
"tsin": "112005, 112007"
}
}
}
};
});
Notice:
- The formatting of the incoming data needs improvement for my requirements.
The sizes, prices, and tsin are stored as strings. They are split when reaching the view:
<form ng-app="app" ng-controller="Ctrl" ng-init="item = this">
<div class="color-pick"
ng-repeat="(key, val) in productData.colors_and_sizes.data track by $index">
<input
type="radio"
name="colors"
hidden="true"
ng-model="item.myColor"
ng-value="key" />
<img
ng-click="item.myColor = key"
ng-src="{{val.swatch_image}}"
alt="">
{{key}}
<div class="size-pick" ng-show="item.myColor==key">
<select
ng-model="item.mySize"
<!--split the sizes into an array named choice -->
<!--idx as choice could represent the index to get the key but it disrupts the value; cannot do (idx, choice) as choice for (idx, choice) in val.sizes.split(',') -->
ng-options="choice as choice for (idx, choice) in val.sizes.split(',')">
<option value="">Please select a size</option>
ng-change="setCurrentPrice(val.sizes.split(',')[idx])"
</select>
</div>
</div>
</form>
In the end, I aim to display 4 values on the view:
mySize: {{ item.mySize}}
myColor: {{item.myColor}}
myPrice: {{item.currentPrice}}
myTsin: {{item.myTsin}}
Once again, please review the old fiddle linked above