这里我必须计算产品检查并添加到购物车时的总价。我能如何实现这一点请帮帮我?
<div ng-app="myApp" ng-controller="startCtrl">
<div ng-repeat="x in names">
<input type="checkbox" ng-model="item.isSelected" ng-change="value(item.isSelected,x)"/>{{x.name}} {{x.price}}
</div>
<hr/>
<div>Selected Item</div>
<div ng-repeat="y in selectedItems" ng-show="selectedItems.length>0">
{{y.name}}----{{y.price}}
</div>
<div ng-show="selectedItems.length<=0"> No item selected </div>
</div>
<script>
var app=angular.module("myApp",[]);
app.controller("startCtrl",function($scope){
$scope.names=[{name:"mobile",price:"100"},{name:"Laptop",price:"200"},{name:"bag",price:"50"}];
$scope.selectedItems=[];
$scope.value=function(isSelected,item){
if(isSelected==true){
$scope.selectedItems.push(item);
}
else {
console.log(item.name);
angular.forEach($scope.selectedItems, function(itemRmv,$index){
if(itemRmv.name==item.name) {
$scope.selectedItems.splice($index,1);
}
})
}
}
});
答案 0 :(得分:2)
我想创建一个过滤器,它会为您提供selectedItems
的总价。
然后,您可以在selectedItems
上应用该过滤器。
过滤强>
app.filter('getprice', function () {
return function (value, property) {
var total = 0;
angular.forEach(value, function (val, index) {
total = total + parseInt(val.price)
});
return total;
}
});
<强> HTML 强>
<div ng-controller="startCtrl">
<div>Total Price {{selectedItems| getprice}}</div>
<div ng-repeat="x in names">
<input type="checkbox" ng-model="item.isSelected" ng-change="value(item.isSelected,x)" />{{x.name}} {{x.price}}</div>
<hr/>
<div>Selected Item</div>
<div ng-repeat="y in selectedItems" ng-show="selectedItems.length>0">{{y.name}}----{{y.price}}</div>
<div ng-show="selectedItems.length<=0">No item selected</div>
</div>
希望这可以帮到你。感谢。
答案 1 :(得分:1)
我会使用整数值替换名称数组中的价格字符串值,然后在添加和删除项目时保留总值
<div ng-app="myApp" ng-controller="startCtrl">
<div ng-repeat="x in names">
<input type="checkbox" ng-model="item.isSelected" ng-change="value(item.isSelected,x)"/>{{x.name}} {{x.price}}
</div>
<hr/>
<div>Selected Item</div>
<div ng-repeat="y in selectedItems" ng-show="selectedItems.length>0">
{{y.name}}----{{y.price}}
</div>
<div>{{total}}</div>
<div ng-show="selectedItems.length<=0"> No item selected </div>
</div>
<script>
var app=angular.module("myApp",[]);
app.controller("startCtrl",function($scope){
$scope.total = 0;
$scope.names=[{name:"mobile",price:100},{name:"Laptop",price:200},{name:"bag",price:50}];
$scope.selectedItems=[];
$scope.value=function(isSelected,item){
if(isSelected==true){
$scope.selectedItems.push(item);
$scope.total += item.price;
}
else {
$scope.total -= item.price;
console.log(item.name);
angular.forEach($scope.selectedItems, function(itemRmv,$index){
if(itemRmv.name==item.name) {
$scope.selectedItems.splice($index,1);
}
})
}
}
});
</script>