所以我有一个小应用程序,用户可以玩折扣来查看产品的价格。他们选择了一种来自下拉菜单的产品 - 一个ng-repeat,然后他们选择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) }}
这样的事情可能吗?如果是这样,我可以真正使用一些指导如何解决这个问题。谢谢你的阅读!
答案 0 :(得分:2)
app.filter('discount', function(){
return function(input, discount){
if (input) return input*(1-discount);
}
})
在你的HTML中
{{itemSelected.price | discount : discount1}}
这是example
修改强>
如果你想使用你的对象确定折扣(在我看来这是一个糟糕的结构,但也许你是为了演示目的)那么你可以在控制器中拥有这段代码
$scope.discount = ($scope.user.discount1 && $scope.discount1)||($scope.user.discount2 && $scope.discount2)
并在html中使用
{{itemSelected.price | discount : discount}}
答案 1 :(得分:1)
不确定你是否真的需要过滤器,没有一个这个计算相当容易:
<p ng-if="itemSelected && user">Your #1 price:
{{itemSelected.price * (user.discount1 ? 1- discount1 : 1) | number : 2}}</p>