有没有办法在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/
当前回答
为什么不把整个数学对象包装在一个过滤器中呢?
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'}}
其他回答
更好的选择是使用:
{{(100*score/questionCounter) || 0 | number:0}}
在值未初始化的情况下,它将方程的默认值设置为0。
为什么不把整个数学对象包装在一个过滤器中呢?
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中做一个简单的循环,你可以很容易地在表达式中设置过滤器。例如:
{{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>
使用管道的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'}}