gpt4 book ai didi

javascript - 具有多种功能的 Angular 自定义计算器

转载 作者:行者123 更新时间:2023-12-04 17:54:21 24 4
gpt4 key购买 nike

我需要一些关于测试计算器的帮助。
我设法让“添加”功能正常工作,但我卡住下一步要做什么,以便在按下“计算”按钮时添加额外的功能,例如“乘法”。

这是一个JSFiddle Link ,我还将添加大部分代码。
我选择了 Angular,但 jQuery 示例也可以。

Examples of the calculator lifecycle might be:

JS

angular.module('myApp', [])

.controller('MyController', function ($scope) {

$scope.items = [];

$scope.addItem = function(){
$scope.items.push({
myOperation: $scope.selectedOperation,
myNumber: $scope.selectedNumber
});

$scope.selectedOperation = '';
$scope.selectedNumber = '';
};

$scope.AddToTotal = function(){
var total = 0;
for(var i=0; i<$scope.items.length; i++){
total += $scope.items[i].myNumber;
}
return total;
}
});

HTML

<body ng-app="myApp">
<div ng-controller="MyController" class="container">
<div class="row">
<div class=".col-md-6 .col-md-offset-3">
<form role="form" class="form-inline">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<!--Select-->
<select ng-model="selectedOperation" class="form-control input-lg" id="operators">
<option value="Add">Add</option>
<option value="Multiply">Multiply</option>
<option value="Apply">Apply</option>
</select>
<!--Input-->
<input ng-model="selectedNumber" class="form-control input-lg" type="number" placeholder="enter a number" />
<!--AddStep-->
<button ng-click="addItem()" id="btnAdd" class="btn btn-default btn-lg">Add step</button>
<p>{{selectedOperation}} {{selectedNumber}} = {{ AddToTotal()}}</p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<ol id="instructions" class="jumbotron" style="margin-top: 2em;">
<li ng-repeat="item in items">{{item.myOperation}} {{item.myNumber}}</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<button ng-click="getTotal()" id="btnCalculate" class="btn btn-primary btn-lg">
Calculate
</button>
<button id="btnReset" class="btn btn-danger btn-lg">Reset</button>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h2>Result:
<span id="result" class="result">{{ AddToTotal() }}</span>
</h2>
</div>
</div>
</form>
</div>
</div>
</div>

最佳答案

用这个更新你的 AddToTotal 函数:

   $scope.AddToTotal = function() {
var total = 0;
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].myOperation === 'Add') {
total += $scope.items[i].myNumber;
} else if ($scope.items[i].myOperation === 'Divide') {
total /= $scope.items[i].myNumber;
} else if ($scope.items[i].myOperation === 'Subtract') {
total -= $scope.items[i].myNumber;
} else if ($scope.items[i].myOperation === 'Multiply') {
total *= $scope.items[i].myNumber;
}
}
return total;
}

关于javascript - 具有多种功能的 Angular 自定义计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com