1

有一个对象有

objData.pendingCount = '2',objData.refundCount = '1',objData.saleCount = 43;

我表演了

<td ng-bind="(objData.pendingCount / objData.saleCount * 100).toFixed(2)"></td>

这工作正常,但是当我这样做时

<td ng-bind="(objData.pendingCount +objData.refundCount)/ objData.saleCount * 100).toFixed(2)"></td>

这里 + 不是在执行算术运算,而是在连接。我怎样才能做到这一点?

4

3 回答 3

3

I assume that these values come from a text box of some sort (via ng-model). If so, the easiest way to fix this would be to set a type='number' on them and angular will take care of the rest!

<input ng-model="objData.pendingCount" type="number" />
...

The alternative is to simply prefix + to force a number conversion, like so

<span ng-bind="((+objData.pendingCount + +objData.refundCount)/ objData.saleCount * 100).toFixed(2)"></span>

Why you CANNOT use Number(...) to make a string a number in an Angular expression

Using Number to convert the string to a number will not work directly because (from https://docs.angularjs.org/guide/expression)

Context: JavaScript expressions are evaluated against the global window. In Angular, expressions are evaluated against a scope object.

So if you need to use Number you can do something like

$scope.Number = $window.Number;

in your controller before you use it in your expression. The same goes for other global window properties.

于 2015-09-09T11:54:47.860 回答
2

纠正你的表达:

<td ng-bind="(objData.pendingCount +objData.refundCount)/ (objData.saleCount * 100).toFixed(2)"></td>

缺少一个左括号

于 2015-09-09T12:00:39.143 回答
1

我用它解决了

<td ng-bind="(sum(objData.pendingCount,objData.refundCount)/objData.saleCount*100).toFixed(2)"></td>

并在控制器中

$scope.sum = function (a, b) {
   return parseInt(a) + parseInt(b);
}

它工作正常。

于 2015-09-09T12:35:45.833 回答