Angularjs输入文本值取决于另一个输入文本,反之亦然

时间:2016-09-29 05:44:59

标签: angularjs

我有一个显示在表格中的数据数组,该表格是可编辑的,并且希望这些字段相互依赖。

如何通过更改单元格的百分比,更改该行的数量,反之亦然,更改金额,还可以更改百分比?始终核实不超过百分比总和的100%,以及不超过总金额的金额总和。

angular
.module("app", [])
.controller("appController", function ($scope) {

  $scope.Data = [
    {
      Percent: 25.0,
      Value: 1000.0
    },
    {
      Percent: 25.0,
      Value: 1000.0
    },
    {
      Percent: 25.0,
      Value: 1000.0
    },
    {
      Percent: 25.0,
      Value: 1000.0
    }
  ];
  $scope.TotalAmount = 4000.0;
});
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <link rel="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />

</head>
<body ng-app="app">

    <div class="container" ng-controller="appController">
      Total amount: {{TotalAmount}}
        <table class="table table-striped">
          <tr><th>Percent</th><th>Value</th></tr>
            <tr ng-repeat="invoice in Data">
                <td><input type="number" ng-model="invoice.Percent" /></td>
                <td><input type="number" ng-model="invoice.Value" /></td>
            </tr>
        </table>
    </div>

</body>
</html>

5 个答案:

答案 0 :(得分:2)

您可以为每个ng-change使用input(就像@Pravin Erande在评论中所说的那样)。

我为你做了SAMPLE FIDDLE(没有任何计算)

<tr ng-repeat="invoice in Data">
                <td><input type="number" ng-model="invoice.Percent" ng-change="valueChanged($index,invoice.Percent,invoice.Value)" /></td>
                <td><input type="number" ng-model="invoice.Value" ng-change="valueChanged($index,invoice.Percent,invoice.Value)" /></td>
            </tr>



$scope.valueChanged= function(index,precent,value)
  {
    console.log("Index changed "+index+" percent "+precent+" value "+value);
    $scope.Data[index].Percent = 50; // Assign after calculation
$scope.Data[index].Value = 2000; // Assign after calculation
  }

您可以创建一个函数并将$index传递给该函数,并在计算后相应地更新$scope.Data

答案 1 :(得分:0)

在两个输入框中添加ng-change事件

import com.google.gson.{JsonParser}
import org.apache.flume.event.JSONEvent
import org.scalatest.FunSuite

class LogEnricherSpec extends FunSuite {
  test("compares json to json") {

    val parser = new JsonParser()

    assert(parser.parse("""
        {
          "eventType" : "TransferItems",
          "timeMillis" : "1234567890",
          "messageXml":{
            "TransferId" : 123456
          }
        } """.stripMargin)
      ==
      parser.parse("""
        {
          "timeMillis" : "1234567890",
          "eventType" : "TransferItems",
          "messageXml":{
            "TransferId" : 123456
          }
        }
      """.stripMargin))
}
angular
.module("app", [])
.controller("appController", function ($scope) {

  $scope.Data = [
    {
      Percent: 25.0,
      Value: 1000.0
    },
    {
      Percent: 25.0,
      Value: 1000.0
    },
    {
      Percent: 25.0,
      Value: 1000.0
    },
    {
      Percent: 25.0,
      Value: 1000.0
    }
  ];
  $scope.TotalAmount = 4000.0;
  $scope.percentChange=function(index,percent){
     var remainpercent=(100-percent)/($scope.Data.length-1);
     var changerowvalue =$scope.TotalAmount*(percent/100);
     $scope.Data[index].Value=changerowvalue;
     var remainValue=($scope.TotalAmount-changerowvalue)/($scope.Data.length-1);
     for(var i=0;i<$scope.Data.length;i++){
       if(i!==index){
           $scope.Data[i].Percent=remainpercent;
           $scope.Data[i].Value=remainValue;
       }
     }
  };
   $scope.valueChange=function(index,value){
     $scope.Data[index].Percent=(value*100/$scope.TotalAmount);
     var remainValue=($scope.TotalAmount-value)/($scope.Data.length-1);
     var remainpercent=(100-$scope.Data[index].Percent)/($scope.Data.length-1);        
     for(var i=0;i<$scope.Data.length;i++){
       if(i!==index){
           $scope.Data[i].Percent=remainpercent;
           $scope.Data[i].Value=remainpercent;
       }
     }
  };
});

我没有添加负面案例,例如发布值大于总值或%大于100

答案 2 :(得分:0)

以下是您需要的逻辑!

$scope.Data[index].Percent = value/$scope.TotalAmount * 100;

$scope.Data[index].Value = precent/100 * $scope.TotalAmount;

答案 3 :(得分:0)

您可以通过调用基于该标志的单个函数来实现它。

参见工作示例。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">

    <div class="container" ng-controller="appController">
      Total amount: {{TotalAmount}}
        <table class="table table-striped">
          <tr><th>Percent</th><th>Value</th></tr>
            <tr ng-repeat="invoice in Data">
                <td><input type="number" ng-model="invoice.Percent" ng-change="changeCalled(invoice, 'per', $index)"/></td>
                <td><input type="number" ng-model="invoice.Value" ng-change="changeCalled(invoice, 'val' ,$index)" /></td>
            </tr>
        </table>
    </div>

</body>
StringSet StringUnion = make_unique<string[]>(arrSize);

答案 4 :(得分:0)

谢谢大家! 我接受了每个人的一些评论,但我认为它帮助我解决了我的问题。

我举了一个我需要做的例子。

问候!

&#13;
&#13;
angular
            .module("app", [])
            .controller("appController", function ($scope, $filter) {

                $scope.Data = [
                  {
                      Percent: 25.0,
                      Value: 1000.0
                  },
                  {
                      Percent: 25.0,
                      Value: 1000.0
                  },
                  {
                      Percent: 25.0,
                      Value: 1000.0
                  },
                  {
                      Percent: 25.0,
                      Value: 1000.0
                  }
                ];
                $scope.TotalAmount = 4000.0;

                $scope.ValueChanged = function (invoice) {
                    invoice.Value = (invoice.Value == null || invoice.Value.toString() == ".") ? 0 : invoice.Value;
                    invoice.Percent = (invoice.Value * 100.0) / $scope.TotalAmount;
                    CalculateTotals();
                    ValidateValues();
                }

                $scope.PercentChanged = function (invoice) {
                    invoice.Percent = (invoice.Percent == null || invoice.Percent.toString() == ".") ? 0 : invoice.Percent;
                    invoice.Value = $scope.TotalAmount * (invoice.Percent / 100.0);
                    CalculateTotals();
                    ValidateValues();
                }

                function CalculateTotals() {
                    var sumPercent = 0;
                    var sumAmount = 0;
                    angular.forEach($scope.Data, function (item, index) {
                        sumPercent += item.Percent;
                        sumAmount += item.Value;
                    });
                    $scope.CalculatedPercent = sumPercent;
                    $scope.CalculatedAmount = sumAmount;
                }

                function ValidateValues() {
                    IsValidAmount();
                    IsValidPercent();
                }

                function IsValidPercent() {
                    if ($scope.CalculatedPercent == 100.0) {
                        $scope.IsValidPercent = true;
                        $scope.formInvoices.hdCalculatedPercent.$setValidity('valid', true);
                    } else {
                        $scope.IsValidPercent = false;
                        $scope.formInvoices.hdCalculatedPercent.$setValidity('valid', false);
                    }
                }

                function IsValidAmount() {
                    if ($scope.CalculatedAmount == $scope.TotalAmount) {
                        $scope.IsValidAmount = true;
                        $scope.formInvoices.hdCalculatedAmount.$setValidity('valid', true);
                    } else {
                        $scope.IsValidAmount = false;
                        $scope.formInvoices.hdCalculatedAmount.$setValidity('valid', false);
                    }
                }

                $scope.CalculatedPercent = 100.0;
                $scope.CalculatedAmount = $scope.TotalAmount;

                $scope.IsValidPercent = true;
                $scope.IsValidAmount = true;
            })
&#13;
.invalidValue{
            color: red;
            font-weight: bold;
        }
        .validValue{
            color: black;
        }
        .tableWidth{
            width: 500px;
        }
&#13;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
   
   
</head>
<body ng-app="app">

    <div class="container" ng-controller="appController">
        <form role="form" name="formInvoices">
            <table class="table table-condensed table-bordered tableWidth">
                <tr>
                    <td class="col-xs-12"><b>Total amount: </b>{{TotalAmount | currency}}</td>
                </tr>
            </table>
            <table class="table table-striped  table-condensed table-bordered tableWidth">
                <tr>
                    <th>Percent</th>
                    <th>Amount</th>
                </tr>
                <tr ng-repeat="invoice in Data">
                    <td><input type="number" ng-model="invoice.Percent" ng-change="PercentChanged(invoice)" /> %</td>
                    <td>$ <input type="number" ng-model="invoice.Value" ng-change="ValueChanged(invoice)" /></td>
                </tr>
            </table>
            <table class="table table-striped table-condensed table-bordered tableWidth">
                <tr>
                    <td class="col-xs-6" ng-class="{'invalidValue': !IsValidPercent,'validValue': IsValidPercent}">{{CalculatedPercent}} %<input name="hdCalculatedPercent" type="hidden" ng-model="CalculatedPercent" /></td>
                    <td  class="col-xs-6" ng-class="{'invalidValue': !IsValidAmount,'validValue': IsValidAmount}">{{CalculatedAmount | currency}}<input name="hdCalculatedAmount" type="hidden" ng-model="CalculatedAmount" /></td>
                </tr>
            </table>
            <input type="submit" ng-disabled="formInvoices.$invalid" value="Save" />
        </form>
    </div>

</body>
</html>
&#13;
&#13;
&#13;