有没有办法在AngularJS绑定中使用数学函数?
如。
<p>The percentage is {{Math.round(100*count/total)}}%</p>
这把小提琴说明了这个问题
http://jsfiddle.net/ricick/jtA99/1/
有没有办法在AngularJS绑定中使用数学函数?
如。
<p>The percentage is {{Math.round(100*count/total)}}%</p>
这把小提琴说明了这个问题
http://jsfiddle.net/ricick/jtA99/1/
当前回答
虽然公认的答案是正确的,你可以注入Math来在angular中使用它,对于这个特定的问题,更传统的/angular方式是数字过滤器:
<p>The percentage is {{(100*count/total)| number:0}}%</p>
你可以在这里阅读更多关于数字过滤器的信息:http://docs.angularjs.org/api/ng/filter/number
其他回答
使用Angular进行简单计算的最简单方法是根据需要直接在HTML标记中进行单个绑定,假设你不需要在页面上进行大量计算。这里有一个例子:
{{(data.input/data.input2)| number}}
在本例中,您只需在()中进行数学运算,然后使用筛选器|来获得数字答案。这里有更多关于将Angular数字格式化为文本的信息:
https://docs.angularjs.org/api/ng/filter
更好的选择是使用:
{{(100*score/questionCounter) || 0 | number:0}}
在值未初始化的情况下,它将方程的默认值设置为0。
如果你想在Angular中做一个简单的循环,你可以很容易地在表达式中设置过滤器。例如:
{{val | number:0}}
有关其他数字过滤器选项,请参阅这个CodePen示例&。
关于使用数字过滤器的Angular文档
将全局Math对象绑定到作用域(记住使用$window而不是window)
$scope.abs = $window.Math.abs;
在你的HTML中使用绑定:
<p>Distance from zero: {{abs(distance)}}</p>
或者为特定的Math函数创建一个过滤器:
module.filter('abs', ['$window', function($window) {
return function(n) {
return $window.Math.abs($window.parseInt(n));
};
});
在你的HTML中使用过滤器:
<p>Distance from zero: {{distance | abs}}</p>
我认为最好的方法是创建一个过滤器,就像这样:
myModule.filter('ceil', function() {
return function(input) {
return Math.ceil(input);
};
});
然后标记看起来像这样:
<p>The percentage is {{ (100*count/total) | ceil }}%</p>
更新小提琴:http://jsfiddle.net/BB4T4/