多个范围输入同步,总是提供相同的总和

时间:2015-06-10 21:32:01

标签: javascript angularjs

所以我试图创建一个页面,我可以为可变数量的人划分给定的金额。该除法的总和必须始终相同并等于初始值。

我面临很多困难,因为AngularJS上的范围输入总是返回一个字符串,所以我必须将它转换为float,然后将它乘以100,这样我就可以在不面对浮点精度问题的情况下进行计算

另一个问题是,当人员之间的划分不准确时,如100€/ 3,它将给出33,3333(3)。我理想的做法是这样的:33,33 + 33,33 + 33,34。

与之前的问题相关,有时我会获得超过2位小数的值。

你可以在这个codepen中找到一个工作的例子,当一个范围输入被改变时,所有其他的输入以相反的方式更新(当我增加一个时,其他的必须减少,反之亦然)。

注意:通过点击和拖动工作范围输入不必点击您想要的位置(它们用于触摸设备),您也只能在&#时移动它们34;等量"被禁用。

控制器代码在这里:

angular.module('ionicApp')   
.controller('HomeTabCtrl', function($scope) {
  $scope.stuff = {
    persons: [],
    max: 100,
    equal: true

  };

  $scope.addPerson = function(){
    var person = {
      expenseValue: 0   
    };

    $scope.stuff.persons.push(person);
    $scope.recalcTotal(-1);
  };

  $scope.recalcTotal = function(index){
    var i = 0;
    var length = $scope.stuff.persons.length;

    if($scope.stuff.equal){

      var equalExpense = $scope.stuff.max / length;

      for(i = 0; i < length; i++){
        $scope.stuff.persons[i].expenseValue = equalExpense;
      }

    }else if(index > 0){
      var total = 0;
      var delta = 0;
      var i = 0;


      for (i = 0; i < length; i++) {
        $scope.stuff.persons[i].expenseValue = parseFloat($scope.stuff.persons[i].expenseValue) * 100;
        total += $scope.stuff.persons[i].expenseValue;
      }

      delta = ($scope.stuff.max * 100 - total)/length;


        for (i = 0; i < length; i++) {
          if(i !== index){
            $scope.stuff.persons[i].expenseValue = _calcNewValue(delta, $scope.stuff.persons[index].expenseValue, $scope.stuff.persons[i].expenseValue);
          }
        }
        $scope.stuff.persons[index].expenseValue = $scope.stuff.persons[index].expenseValue / 100;
      }
  };

  function _calcNewValue(delta, value, userExpense){

    var newValue =  userExpense + delta;


    if (newValue < 0 || value === $scope.stuff.max * 100){
      newValue = 0;
    }
    else if (newValue > $scope.stuff.max * 100){
      newValue = $scope.stuff.max * 100;
    }

    return newValue / 100;
  }
});

0 个答案:

没有答案
相关问题