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

如。

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

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

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


当前回答

如果你想在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/

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

你可以用最简单的方法

$scope.Math = window.Math;

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

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

{{val | number:0}}

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

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

这或多或少是三个答案的总结(来自Sara Inés Calderón, klaxon和Gothburz),但由于他们都添加了一些重要的东西,我认为值得加入解决方案并添加更多的解释。

考虑到你的例子,你可以在你的模板中使用:

{{ 100 * (count/total) }}

然而,这可能会导致大量的小数点,所以使用过滤器是一个很好的方法:

{{ 100 * (count/total) | number }}

默认情况下,数字过滤器将留下最多三个小数位数,这就是fractionSize参数非常方便的地方 ({{100 * (count/total) | number:fractionSize}}),这在你的情况下将是:

{{ 100 * (count/total) | number:0 }}

This will also round the result already: angular.module('numberFilterExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.val = 1234.56789; } ]); <!doctype html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body ng-app="numberFilterExample"> <table ng-controller="ExampleController"> <tr> <td>No formatting:</td> <td> <span>{{ val }}</span> </td> </tr> <tr> <td>3 Decimal places:</td> <td> <span>{{ val | number }}</span> (default) </td> </tr> <tr> <td>2 Decimal places:</td> <td><span>{{ val | number:2 }}</span></td> </tr> <tr> <td>No fractions: </td> <td><span>{{ val | number:0 }}</span> (rounded)</td> </tr> </table> </body> </html>

最后要提到的是,如果你依赖于外部数据源,提供一个合适的回退值可能是一个很好的实践(否则你可能在你的网站上看到NaN或什么都没有):

{{ (100 * (count/total) | number:0) || 0 }}

旁注:根据您的规格,您甚至可以更精确地使用回退/已经在较低级别上定义回退(例如{{(100 * (count || 10)/ (total || 100) | number:2)}})。然而,这可能并不总是有意义的。