如何使用角度js从动态生成的表及其行计算值?

问题描述 投票:1回答:2

我试图从表中找到净值的价值。

Net Worth = Sum(Stock Price * Shares Held)

下面是根据用户选择创建的表。 Table for stocks

例如:从上表中,净值=(842.21 * 1 + 230.16 * 2 + 1002.2 * 2)。

我正在尝试使用ng-change,因为每次用户添加或删除股票时networth都会发生变化。此外,我也面临着css问题,因为当一行被添加到表时networth会失败。

Here is the plnkr

  <section class="pickstocks">
    <label class="basiclabel">Manage Portfolio</label>
    <div class="pickstocks-align">
        <table>
            <thead>
                <tr>
                    <th>STOCK</th>
                    <th>PRICE</th>
                    <th>SHARES</th>
                    <th>WEIGHT</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                    <td>{{stock.key}}</td>
                    <td class="portfoliovalue">{{"&#x20b9;" + stock.value}}</td>
                    <td class="changer">
                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                    </td>
                    <td>{{stock.weight}}</td>
                </tr>
            </tbody>
        </table>
        <div class="networth">
            <h3>Networth</h3>
        </div>
    </div>
</section>
javascript css angularjs
2个回答
3
投票

这是Plunker供参考

首先要做的是将weight字段存储为stock对象中的另一个字段。

mystock.weight = function(){return this.value*this.shares};

使它成为sharesvalue字段的函数让我们更新动态改变networth的其他两个字段。另外,将股票作为字段添加到股票对象中可以让我们以后更容易地更新它,因此我们只需要像这样增加/减少字段。

$scope.stocksArray[$scope.stocksArray.indexOf(stock)].shares++;

改变代码的最大部分是客观化它。获取股票并用对象表示它使我们可以在以后轻松修改和访问这些值。

完成后,您所要做的就是创建一个返回所有权重之和的方法。

$scope.getNetWorth = function(){
      let total = 0;

      for(let i = 0; i < $scope.stocksArray.length; i++){
        total += $scope.stocksArray[i].weight()
      }

      return total.toFixed(2);
    }

然后在html中引用它,就像{{"&#x20b9;" +getNetWorth()}}一样

将来尝试使用OOP实践来简化代码并将数据转换为对象表示,这将节省您的时间,让您在以后尝试操作和访问数据时感到头疼。


0
投票

你需要计算每个实例的总和

 <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                    <td>{{stock.key}}</td>
                    <td ng-init="totalAmount = totalAmount + (stock.value*stock.index)" class="portfoliovalue">{{"&#x20b9;" + stock.value}}</td>
                    <td class="changer">
                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                    </td>
                    <td>{{stock.weight}}</td>
                </tr>

总数将是

<div class="networth">
        <h3>{{totalAmount }}</h3>
    </div>
© www.soinside.com 2019 - 2024. All rights reserved.