有没有办法在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进行简单计算的最简单方法是根据需要直接在HTML标记中进行单个绑定,假设你不需要在页面上进行大量计算。这里有一个例子:
{{(data.input/data.input2)| number}}
在本例中,您只需在()中进行数学运算,然后使用筛选器|来获得数字答案。这里有更多关于将Angular数字格式化为文本的信息:
https://docs.angularjs.org/api/ng/filter
其他回答
我认为最好的方法是创建一个过滤器,就像这样:
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对象绑定到作用域(记住使用$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'}}
这看起来不像是一种非常Angular的方式。我不完全确定为什么它不起作用,但您可能需要访问作用域才能使用这样的函数。
我的建议是创建一个过滤器。这就是Angular的方式。
myModule.filter('ceil', function() {
return function(input) {
return Math.ceil(input);
};
});
然后在你的HTML中这样做:
<p>The percentage is {{ (100*count/total) | ceil }}%</p>