AngularJS我正在尝试计算嵌套ng重复中包含的许多输入(ng模型)的结果

AngularJS I am trying to calculate the result of many inputs (ng-model) included inside nested ng-repeat

本文关键字:ng 许多 包含 输入 结果 模型 AngularJS 嵌套 计算      更新时间:2023-09-26

我正在学习AngularJS,并试图为几种产品创建一个简单的库存控制程序。我已经在谷歌上搜索了几个小时,浏览了很多问题,但还没能让我的代码正常工作。

每个产品应计算的公式为:

  • 最终库存=初始库存+生产-销售

这是代码:http://codepen.io/swordf1zh/pen/zfwcB

HTML

<div ng-app="inventory">
    <form role="form" class="row" ng-controller="ProdCtrl">
        <!-- Secciones -->
        <div class="col-md-3" ng-repeat="section in sections">
            <blockquote class="text-center">{{section.name}}</blockquote>
            <div ng-repeat="product in products">
                <div class="form-group">
                    <div class="input-group">
                      <span class="input-group-addon">{{product.name}}</span>
                      <input type="number" 
                             class="form-control text-center" 
                             placeholder="Cantidad" 
                             ng-model="total" 
                             ng-change="calculate(section.id, product.id, total)">
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <blockquote class="text-center">Final Inventory</blockquote>
            <div ng-repeat="product in products">
                <div class="form-group">
                    <div class="input-group">
                      <span class="input-group-addon">{{product.name}}</span>
                      <p class="form-control text-center">{{product.total}}</p>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

JS

var app = angular.module("inventory",[]);
app.controller("ProdCtrl", ['$scope',
    function($scope) {
        $scope.sections = [
            {id:1, name:'Initial Inventory'},
            {id:2, name:'Production'},
            {id:3, name:'Sales'},
        ];
        $scope.products = [
            {id:1, name:'Prod1', total:0},
            {id:2, name:'Prod2', total:0},
            {id:3, name:'Prod3', total:0},
            {id:4, name:'Prod4', total:0}
        ];
        $scope.calculate = function( sectionId, productId, cantidad ){
            if( sectionId != 3 ){
                $scope.products[productId-1].total += cantidad;
            } else {
                $scope.products[productId-1].total -= cantidad;
            }
        };
    }
]);

您的js代码中存在问题

首先,您正在与section进行比较。它应该是if循环中的sectionId。其次,将参数作为cantidad接收的计算方法应该解析为Integer值。

所以你的工作代码笔

和我更改的JS代码(计算函数)

   $scope.calculate = function( sectionId, productId, cantidad ){
     var inventoryEdit = parseInt(cantidad);
            if( sectionId != 3 ){
        $scope.products[productId-1].total += inventoryEdit;
      } else {
        $scope.products[productId-1].total -= inventoryEdit;
      }
   };