【问题标题】:Value being cleared in DOM by ng-model AngularJSng-model AngularJS 在 DOM 中清除值
【发布时间】:2013-04-04 01:19:05
【问题描述】:

我对 AngularJS 很陌生,遇到了一些我自己似乎无法弄清楚的事情。我正在开发发票应用程序,当我返回一个值和一个 ng-model 时,该值正在计算中,但从未在 DOM 中设置。然后它又永远不会更新我要计算的小计。

rowController.cshtml

<tr id="row-{{$index+1}}" class="item-row" ng-repeat="item in itemRows">
    <td><input type="text" class="text-right" placeholder="$0.00" ng-model="hrsQty" /></td>
    <td><input type="text" class="text-right" placeholder="$0.00" ng-model="ratePrice" /></td>
    <td><input type="text" class="text-right" placeholder="$0.00" value="{{rowTotal(hrsQty, ratePrice) | currency}}" ng-model="amountSum[$index]" /></td>
</tr>

这段代码采用 hrsQty * ratePrice 并将其值返回到最后输入的文本中。返回的值将通过for 循环发送

Controller.js

function InvoiceController($scope) {
$scope.itemRows = [0, 1, 2, 3, 4];
$scope.hrsQty;
$scope.ratePrice;
$scope.amountSum = [];
$scope.subTotal;

$scope.rowTotal = function (hrsQty, ratePrice) {
    return hrsQty * ratePrice;
};

$scope.subTotal = function () {
    var sum = 0;

    for (var i = 0, v; v = $scope.amountSum[i]; i++) {
        sum += +v;
    }
    return sum;
};
}

如果我删除 ng-model,那么我的计算会完美返回,但如果我将 ng-model 放回原处并删除 value="{{rowTotal(hrsQty, ratePrice) | currency}}",那么我的小计计算效果很好。当两者结合时,value="{{rowTotal(hrsQty, ratePrice) | currency}}" 永远不会在 DOM 中设置或被删除。

任何帮助将不胜感激。

【问题讨论】:

  • amountSum 字段应该是可编辑的还是仅供参考?
  • 这是我仍然需要改变的地方。它将是只读的。

标签: html css asp.net-mvc angularjs


【解决方案1】:

我假设您不需要 ng-model,而只是显示一些价值。 ng-model 应该用于允许用户更改模型中的某些内容。

所以检查这个解决方案: http://plnkr.co/edit/eo37EXog0FWVr1lTn1Cw?p=preview

看起来像你需要的东西。

【讨论】:

  • 我一直在搞乱 plnkr 解决方案,并将其全部实施到我的解决方案中。当我输入第一个字段 33.33 和第二个字段 3 时,subTotal 和 rowTotal 是不同的。我该如何解决?还有 |0 是什么意思?谢谢!
  • 我发现了这个 -jsfiddle.net/slav123/75m7e/3 我编辑了我的 .js 和代码以遵循该示例,现在能够取回正确的结果。再次感谢@Valentyn
  • 关于总数不同 - 这是因为我对结果进行了四舍五入(按“|0”)。我已经更新了 plunker。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 2017-11-19
  • 2015-12-05
  • 2015-07-14
  • 1970-01-01
相关资源
最近更新 更多