AngularJS - 使用输入选项动态更改表达式

AngularJS - changing expression dinamically with input options

我正在构建一个应用程序,其中项目的价格应该以不同的货币显示。对于购物车,我使用 angular 指令,NgCart 我需要在其中传递每件商品的数量和价格。这个指令有一个独立的范围,所以我不能使用过滤器来切换货币,而是直接从范围中传递不同的价格。我只能从指令内的一个范围传递数据(来自 name in names 的数据)。

我想做的是,当在输入选项元素中选择相应的选项时,显示的价格会发生变化,并且通过切换它,传递给指令的价格也会发生变化(到所选货币).我一直在尝试使用 ng-options 来实现它,但有些东西不起作用。我的 html 是这样的:

<div ng-controller="myCtrl" ng-app="myApp">
  <select ng-options="price.currency for price in names" ng-model="currency"></select>  
  <div ng-repeat="name in names">
    The price of {{name.toy}} is {{name.price[0].amount}} {{name.price[0].symb}}
    <ngcart-addtocart name="{{name.toy}}" price="{{name.price[0].priceUSD}}">  
        <p1>Add to Cart</p1>
    </ngcart-addtocart>
    <br>
    <br>
  </div>
</div>

我的控制器:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = [{
      "toy": "Buzz Lightyear",
      "price": [
          {"currency":"usd","amount":199,"symb": "$"},
          {"currency":"eur","amount": 179,"symb": "€"}
      ]
    },
    {
      "toy": "Woody",
      "price": [
          {"currency":"usd","amount":179,"symb": "$"},
          {"currency":"eur","amount": 169,"symb": "€"}
      ]
    }]; 
 });

您可以看到一个有效的 JSfiddle here 提前致谢!

编辑: 使用 ng-cart 指令更新 plunker,剩下的问题是使用 Iulian 提供的解决方案,我无法传递货币符号,因此我无法显示正确的单位。

您的代码存在几个问题。

1.首先,你对ngOptions的用法是不正确的。您使用 for price in names,因此从您的名称中获取每个对象作为 price,即 {"toy": ..., "price": []} 对象。相反,我建议您创建另一个变量来保存可用货币,例如:
$scope.currencies = [
  {currency: 'usd', symb: '$'},
  {currency: 'eur', symb: '€'}
];
2. 您不会在指令中获得更新的价格,因为您始终将价格的第一个元素传递给它:price="{{name.price[0].priceUSD}}"。相反,您需要根据所选货币动态获取它。为此,您可以创建一个类似于以下函数的函数,该函数将 return 给定货币的价格:
$scope.getPriceInCurrency = function (item, currency) {
  var priceInCurrency = 0;
  item.price.forEach(function(price) {
    if (price.symb === currency) {
      priceInCurrency = price.amount;
    }
  });
  return priceInCurrency;
};

现在在显示选项的时候,想显示对应的价格,用上面的函数获取:

The price of {{name.toy}} is {{getPriceInCurrency(name, currency)}} {{currency}}

在将值传递给 ngcartAddtocart 指令时,您可以省略 {{}} 大括号,因为此处不需要大括号。

这是您 fiddle 的 fork 和一个工作示例。

祝你好运!

由于 names 是一个数组对象,因此很难区分是 names[0] 还是 names[1]。

 <select ng-options="item.currency for item in names[1].price" ng-model="curr"></select>  

因此,如果您为货币查找创建一个单独的数组,那么问题就解决了。

 <select ng-options="item as item.currency for item in currencyLookup" ng-model="selected"></select>
 $scope.currencyLookup=[
 {"currency":"usd","symb": "$"},
 {"currency":"eur","symb": "€"}
 ]