所以我有一个小应用程序,用户可以使用折扣来查看产品的价格。他们选择一个来自下拉列表的产品 - 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/