下面是我的角度JS网页应用程序的JS:
$scope.total = 50000000;
var ref = databaseService.players;
$scope.players = $firebaseArray(ref);
$scope.picked = [];
$scope.history = [];
$scope.buy = function(player) {
//remove if already added locally
var index = $scope.history.indexOf(player);
var index2 = $scope.picked.indexOf(player.id);
if(index>=0 || index2>=0 ){
$scope.history.splice(index,1);
$scope.picked.splice(index2,1);
PlayerService.removePlayerFromSelection(player);
return;
}
//max 6 allowed
if($scope.history.length>=6 || $scope.picked.length>=6){
alert('max 6 allowed');
return;
}
//to make sure moeny doesn't go below $50,000,000
if($scope.total<0){
alert('Oops! You have run out of cash');
return;
}
var selected = $scope.history.reduce(function(a,b){
a[b.position] = (a[b.position] || 0) + 1;
return a;
}, {}) || {};
if(!selected[player.position] || selected[player.position]<2 && $scope.total>0){
$scope.history.push(player);
$scope.picked.push(player.id);
PlayerService.addPlayerToSelection(player);
}else{
alert('You can add only two players per position');
}
};
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
return tot;
if (tot <0){
alert('Oops! You have run out of money')
}
}, $scope.total);
};
$scope.saveTeam = function(){
userRef.set( $scope.picked);
$location.path('/mySquad');
};
我的问题
有没有办法在总数低于 0 时提醒用户?我尝试在 buy(( 函数中添加一个 if 语句,但它不起作用。我的目标是在总预算低于 0 时提醒用户。
另类
我厌倦的另一个选项是禁用"保存团队"按钮,如果函数的结果getTotal
导致值小于 0。以下是我尝试但未成功的 HTML 代码:
<button type="submit" class="btn btn-lg btn-primary btn-md " ng-disabled="history.length<6" ng-disabled="getTotal<0" ng-click="saveTeam()" > Save Team </button>
你能尝试重写函数,如下所示吗?您需要更改退货声明的位置
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
if (tot <0){
alert('Oops! You have run out of money')
}
return tot; //changed location of this line
}, $scope.total);
};
在这里,返回语句后的代码不会执行。 删除return tot
或将其移动到下面 if 条件。
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
return tot; // wrong place of return statement
if (tot <0){ // it won't execute, coz, it was returned before line itself
alert('Oops! You have run out of money')
}
},
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
if (tot <0){
alert('Oops! You have run out of money')
return tot; // If you place here once you come here it will return
}
},