【发布时间】:2016-08-26 07:54:08
【问题描述】:
此函数有效,但如何避免为第二个变量键入相同的 for 循环并以某种方式只使用一个。尽量不要在这里重复 yuorself 方法。我需要使用数组吗?
JS:
var app=angular.module('xpCalc', []);
app.controller('xpCalculatorController', function($scope){
$scope.currentLevel=1;
$scope.currentXp=function(){
var output=0;
for (var thisLVL=1; thisLVL < $scope.currentLevel; thisLVL++) {
output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
}
return output;
};
$scope.desiredLevel=1;
$scope.desiredXp=function(){
var output=0;
for (var thisLVL=1; thisLVL < $scope.desiredLevel; thisLVL++) {
output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
}
return output;
};
});
HTML:
<h2>{{desiredXp()-currentXp()}}</h2>
【问题讨论】:
-
首先,在控制器或服务中计算
desiredXp()-currentXp()。在 HTML 中发布结果后。此外,使用::bindOnce,例如<h2>{{::result}}</h2>。无论如何,在 HTML 中使用函数并不是一个好习惯,你在每个摘要周期都调用它 -
实现
getXP(level)函数即可。
标签: javascript html angularjs function dry