有没有办法在AngularJS绑定中使用数学函数?

如。

<p>The percentage is {{Math.round(100*count/total)}}%</p>

这把小提琴说明了这个问题

http://jsfiddle.net/ricick/jtA99/1/


当前回答

你必须将Math注入你的作用域,如果你需要使用它 $scope对数学一无所知。

你可以用最简单的方法

$scope.Math = window.Math;

在控制器中。 Angular的正确方法是创建一个Math服务。

其他回答

如果你想在Angular中做一个简单的循环,你可以很容易地在表达式中设置过滤器。例如:

{{val | number:0}}

有关其他数字过滤器选项,请参阅这个CodePen示例&。

关于使用数字过滤器的Angular文档

更好的选择是使用:

{{(100*score/questionCounter) || 0 | number:0}}

在值未初始化的情况下,它将方程的默认值设置为0。

将全局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/

为什么不把整个数学对象包装在一个过滤器中呢?

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'}}