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

如。

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

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

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


当前回答

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

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

其他回答

使用Angular进行简单计算的最简单方法是根据需要直接在HTML标记中进行单个绑定,假设你不需要在页面上进行大量计算。这里有一个例子:

{{(data.input/data.input2)| number}} 

在本例中,您只需在()中进行数学运算,然后使用筛选器|来获得数字答案。这里有更多关于将Angular数字格式化为文本的信息:

https://docs.angularjs.org/api/ng/filter

使用管道的Angular Typescript示例。

math.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'math',
})

export class MathPipe implements PipeTransform {

  transform(value: number, args: any = null):any {
      if(value) {
        return Math[args](value);
      }
      return 0;
  }
}

添加到@NgModule声明中

@NgModule({
  declarations: [
    MathPipe,

然后在模板中像这样使用:

{{(100*count/total) | math:'round'}}

数字过滤器使用数千个分隔符格式化数字,因此它不是严格意义上的数学函数。

此外,它的小数“限制器”并没有限制任何小数(正如其他一些答案会让你相信的那样),而是四舍五入。

因此,对于任何你想要的数学函数,你可以像这样注入它(模仿比注入整个math对象更容易):

myModule.filter('ceil', function () {
  return Math.ceil;
});

也不需要将它包装在另一个函数中。

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

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

这或多或少是三个答案的总结(来自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)}})。然而,这可能并不总是有意义的。