我正在尝试从表中找出净 Assets 的值。
净 Assets = Sum(股票价格 * 持有股份)
例如:根据上表,净 Assets = (842.21*1 + 230.16*2 + 1002.2*2)。
我正在尝试使用 ng-change,因为每次用户添加或删除股票时净值都会发生变化。此外,我还面临 css 问题,因为当向表中添加一行时 networth 下降。
<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">{{"₹" + 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>
最佳答案
这是 Plunker供引用
首先要做的是像存储 stock
对象中的另一个字段一样存储 weight
字段。
mystock.weight = function(){return this.value*this.shares};
将其变成 shares
和 value
字段的函数让我们可以动态更新其他两个字段,从而改变 networth
。此外,将 shares 作为一个字段添加到 stock 对象中可以让我们以后更轻松地更新它,因此我们只需要像这样增加/减少该字段。
$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 中引用它 {{"₹"+getNetWorth()}}
在未来尝试使用 OOP 实践来简化您的代码并将您的数据转换为对象表示,这将节省您的时间并减少您以后尝试操作和访问您的数据的麻烦。
关于javascript - 如何使用angular js从动态生成的表及其行中计算值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44970500/