javascript - AngularJS display different object property via select list -
i have angularjs web app i'm building here (only entrees > breadsticks have items currently)
everything fine, until decided wanted allow user select different size items (either large, medium or small). task has been headache me because need keep track of different prices, different sizes, , different number of orders each size.
currently i'm trying build function return correct price depending depending on select option
selected.
here breadsticks
object we're working with:
$scope.breadsticks = [ { name: 'garlic buttered', pricesm: 2.99, pricemd: 3.99, pricelg: 4.99, sizesm: '6pcs', sizemd: '10pcs', sizelg: '14pcs', description: 'garlic buttery goodness on stick of cheesy bread.', numordersm: 0, numordermd: 0, numorderlg: 0, }, { name: 'mozzarella stuffed', pricesm: 3.49, pricemd: 4.49, pricelg: 5.49, sizesm: '6pcs', sizemd: '10pcs', sizelg: '14pcs', description: 'jam packed mozarella goodness know love.', numordersm: 0, numordermd: 0, numorderlg: 0, } ];
markup
<tbody ng-repeat="breadstick in breadsticks"> <tr> <td> <select id="sizeselect"> <option>choose size</option> <option value="1">small - {{breadstick.sizesm}}</option> <option value="2">medium - {{breadstick.sizemd}}</option> <option>large - {{breadstick.sizelg}}</option> </select> </td> <td> {{breadstick.name}} </td> <td> <script> getprice(); </script> </td>
here attempt:
$scope.getprice = function() { var selectlist = document.getelementbyid("sizeselect"); var selectsize = selectlist.options[selectlist.selectedindex].value; if(selectsize == 1) { return breadstick.pricesm; } else if(selectsize == 2) { return breadstick.pricemd; } };
i'm having problems calling function, though realize not reusable because return breadstick prices... may able add parameter somehow make reusable.
the error getprice() undefined
since in scope, $scope.getprice();
undefined. need print screen different value depending select option chosen.
they way try solve problem not angular way. try using ng-options
instead of select. bind prices it. , use ng-model
selected value:
<table> <tbody ng-repeat="breadstick in breadsticks"> <tr> <td> <select ng-model="breadstick.selecteditem" ng-options="item.title item in [{title:'small - ' + breadstick.pricesm, price:breadstick.pricesm}, {title:'medium - ' + breadstick.pricemd, price:breadstick.pricemd}, {title: 'large - ' + breadstick.pricelg, price:breadstick.pricelg}] track item.price"> </select> </td> <td> {{breadstick.name}} </td> <td>{{breadstick.selecteditem}}</td> </tr> </tbody> </table>
i have changed code work better angular. after select item select, new property added each breadstick object selected item. breadstick.selecteditem.price
gives selected price of breadstick.
here fiddler: https://jsfiddle.net/alisabzevari/fpqtdsh6/3/
you must use angular 1.2+
Comments
Post a Comment