每个使用角度的数组的总和

时间:2017-05-17 07:09:29

标签: javascript angularjs controller

function dialogController(generate, $scope) {
$scope.profiles = generate.get_keys('::role');
$scope.content = {};
$scope.options = [];
$scope.servers = {};
$scope.subs = {};
$scope.discountList = {};
$scope.total = {};

$scope.toggle = function(item, list) {
    var idx = list.indexOf(item);
    if (idx > -1) {
        list.splice(idx, 1);
    } else {
        list.push(item);
    }
};
$scope.contentList = function(name) {
    $scope.content = generate.get_config('::role::' + name).items;
    // console.log($scope.content);
};

$scope.priceMapping = function(subscriptionPrice) {
    var obj = {
        'bronze': [129, 0.5],
        'silver': [165, 0.5],
        'gold': [199, 1],
        'platinum': [265, 1]
    };

    return obj[subscriptionPrice];

};




$scope.calculatePrice = function() {
    angular.forEach($scope.options, function(opt) {
        $scope.discountList[opt] = {};
        $scope.discountList[opt].servers = $scope.servers[opt];
        $scope.discountList[opt].subscription = $scope.subs[opt];

        var price = (Math.pow($scope.servers[opt], 0.75)) * $scope.priceMapping($scope.subs[opt])[0];
        console.log(price);
        var hours = Math.round((($scope.priceMapping($scope.subs[opt])[1]) * (Math.pow($scope.servers[opt], 0.75))) * 10) / 10;
        console.log(hours);


        $scope.discountList[opt].price = price;
        $scope.discountList[opt].hours = hours;

    });

    var totalPrice = 0;
    var totalHour = 0;


};

}

这里我想用每个角度计算总价格和总小时数。 discountList {}中包含价格和小时数。

我如何计算总价和总小时数?

discountList {}包含价格和小时数,那么如何计算它们的总数呢?

2 个答案:

答案 0 :(得分:0)

在控制器中创建一个函数,为你计算它。

<div>Total: {{ getTotalHours() }}</div>
控制器中的

$scope.getTotalHours= function(){
    var total = 0;
    for(var i = 0; i < $scope.discountList.length; i++){
        var item = $scope.discountList[i];
        total += item.hours;
    }
    return total;
}

答案 1 :(得分:0)

问题似乎含糊不清,但这可能是你需要的。 最初,将totalPricetotalHours设置为0,在angular.forEach中迭代每个对象并将其添加到变量中。

$scope.calculatePrice = function() {
    $scope.totalPrice = 0;
    $scope.totalHour = 0;

    angular.forEach($scope.options, function(opt) {
        $scope.discountList[opt] = {};
        $scope.discountList[opt].servers = $scope.servers[opt];
        $scope.discountList[opt].subscription = $scope.subs[opt];

        var price = (Math.pow($scope.servers[opt], 0.75)) * $scope.priceMapping($scope.subs[opt])[0];
        var hours = Math.round((($scope.priceMapping($scope.subs[opt])[1]) * (Math.pow($scope.servers[opt], 0.75))) * 10) / 10;

        $scope.discountList[opt].price = price;
        $scope.discountList[opt].hours = hours;

        $scope.totalPrice += price;
        $scope.totalHour += hours
    });
    console.log("Total Price : ", $scope.totalPrice);
    console.log("Total Hours : ", $scope.totalHour);
};

HTML

<div> Total Price : {{totalPrice}}</div>
<div> Total Hours : {{totalHour}}</div>