Arithmetic addition (+) is not working in ng-bind

心不动则不痛 提交于 2019-12-24 15:19:35

问题


There is an object having

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

I performed

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

this is working fine but when I do

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

Here + is not performing arithmetic opration rather it is concating. How can I achieve this ?


回答1:


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.




回答2:


corrects your expression:

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

is missing an open parentheses




回答3:


I solved it using

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

and in the controller

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

and it is working fine.



来源:https://stackoverflow.com/questions/32478738/arithmetic-addition-is-not-working-in-ng-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!