角度,折扣过滤器 - 将变量传递到过滤器中

Angular, a filter for discounts - passing variables into filter?

本文关键字:过滤器 变量 角度      更新时间:2023-09-26

所以我有一个小应用程序,用户可以在其中玩转折扣以查看产品的价格。他们选择一个来自下拉菜单的产品 - 一个 ng 重复,然后他们选择 1 个折扣中的 3 个,我想尝试以折扣价格显示结果。所以我的第一个想法是也许过滤器可以做到这一点?但我不清楚这是否是正确的方向。

这是我所拥有的

在控制器中 -

$scope.myItems  = [{"id":0,"name":"item1", "price" : 3.50 },{"id":1,"name":"item2", "price" : 5.50 },{"id":2,"name":"item 3", "price" : 4.75 }];
$scope.discount1 = 0.7;
$scope.discount2 = 0.25;
//the users information that tells us which discounts he/she has
$scope.user = {'name' : 'Ted', 'discount1' : false, 'discount2': true};

因此,如果选择折扣来提供折扣价格,折扣将只是一个乘数。

关于我的观点:

<select ng-model="itemSelected" ng-options="item as item.name for item in myItems"> </select>

我想做这样的事情:

<p>Your price:</p>
{{itemSelected.price | (filtered by discounts if true in $scope.user) }}

这样的事情可能吗?如果是这样,我真的可以使用一些关于如何解决这个问题的指导。感谢您的阅读!

app.filter('discount', function(){
  return function(input, discount){
    if (input) return  input*(1-discount);
  }
})

在你的网页中

{{itemSelected.price | discount : discount1}}

这是一个例子

编辑

如果你想使用你的对象来确定折扣(在我看来这是一个糟糕的结构,但也许你是为了演示目的),那么你可以在控制器中有这段代码

$scope.discount = ($scope.user.discount1 && $scope.discount1)||($scope.user.discount2 && $scope.discount2)

并在 HTML 中使用

{{itemSelected.price | discount : discount}}

不确定你是否真的需要过滤器,如果没有过滤器,这个计算是相当容易的:

<p ng-if="itemSelected && user">Your #1 price: 
  {{itemSelected.price * (user.discount1 ? 1- discount1 : 1) | number : 2}}</p>