javascript - Angular,折扣过滤器 - 将变量传递到过滤器中?

标签 javascript angularjs

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

这就是我所拥有的

在 Controller 中 -

$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);
  }
})

在你的html中

{{itemSelected.price | discount : discount1}}

这是一个example

编辑

如果你想使用你的对象确定折扣(在我看来这是一个不好的结构,但也许你是为了演示目的)那么你可以在 Controller 中添加这段代码

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

并在 html 中使用

{{itemSelected.price | discount : discount}}

关于javascript - Angular,折扣过滤器 - 将变量传递到过滤器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183051/

相关文章:

javascript - 将双页添加到turnjs "book"

javascript - AngularJS:ng-controller 多种功能

javascript - 以 ECMAScript 5 及更高版本为目标时,八进制文字不可用

javascript - 使用 AngularJS 将数据库中出现的 HTML 渲染到 View 中

javascript - 使用新数据完全重置 dom-repeat 元素

javascript - if else 变量作用域在 js 的 else 中显示未定义

javascript - 在执行 Angular 2 CLI 项目时如何添加第三方包

javascript - 使用容器的多个实例时 ID 重复

javascript - 为什么我的Grails应用程序无法从Angular脚本中获取对象?

javascript - 不允许 Django + Angular 方法 PUT 和 POST