有没有办法在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/
当前回答
如果你想在Angular中做一个简单的循环,你可以很容易地在表达式中设置过滤器。例如:
{{val | number:0}}
有关其他数字过滤器选项,请参阅这个CodePen示例&。
关于使用数字过滤器的Angular文档
其他回答
你必须将Math注入你的作用域,如果你需要使用它 $scope对数学一无所知。
你可以用最简单的方法
$scope.Math = window.Math;
在控制器中。 Angular的正确方法是创建一个Math服务。
虽然公认的答案是正确的,你可以注入Math来在angular中使用它,对于这个特定的问题,更传统的/angular方式是数字过滤器:
<p>The percentage is {{(100*count/total)| number:0}}%</p>
你可以在这里阅读更多关于数字过滤器的信息:http://docs.angularjs.org/api/ng/filter/number
将全局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>
如果你想在Angular中做一个简单的循环,你可以很容易地在表达式中设置过滤器。例如:
{{val | number:0}}
有关其他数字过滤器选项,请参阅这个CodePen示例&。
关于使用数字过滤器的Angular文档
为什么不把整个数学对象包装在一个过滤器中呢?
var app = angular.module('fMathFilters',[]);
function math() {
return function(input,arg) {
if(input) {
return Math[arg](input);
}
return 0;
}
}
return app.filter('math',[math]);
并使用:
{{number_var | math:'ceil'}}