对对象数组中的对象使用ng-options

时间:2015-06-20 23:03:36

标签: javascript angularjs

我在这里有这个对象数组:

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

我想创建一个仅显示size: { sizeSM: '6 pcs', sizeMD: '10 pcs', priceLG: '14 pcs' }信息的选择列表:

<td>
  <select ng-model="breadstick.selectedItem" ng-options="breadstick.size for breadstick in breadsticks">
  </select>
</td>

<td>
  {{breadstick.selectedItem.price}}
</td>

我还希望在选择列表更改时显示相应的价格。

非常感谢任何对正确方向的帮助或颠簸。

Fiddle Here

2 个答案:

答案 0 :(得分:1)

使用tycho-project对象语法:

ngRepeat

演示:https://jsfiddle.net/vn2ppwp9/1/

编辑:如果您想获得所选商品尺寸的价格,则可以更轻松地重新格式化数据,如下所示:

<td>
    <select ng-model="breadstick.selectedItem" ng-options="size as text for (size, text) in breadstick.size">
    </select>
</td>

现在您可以将视图重复更新为:

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

<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> 函数的位置:

getPrice

答案 1 :(得分:0)

使用 json 过滤器:

<select ng-model="breadstick.selectedItem" ng-options="breadstick.size as (breadstick.size | json) for breadstick in breadsticks">
</select>