Я новичок в разработке JS. На github я нашел проект калькулятора nodejs, которым я манипулировал.
Моя проблема: в моем калькуляторе я пытаюсь объединить все свои результаты вместе. Тем не менее, данные моих старых записей все еще присутствуют, я хотел бы удалить эти старые записи и обновить их с самой последней записью.
Я знаю, что это как-то связано с data-ng-repeat
(показано в моем коде индекса ниже), но я пробовал другие директивы, и они не работали. Что-то мне нужно изменить в моем коде, чтобы использовать другую директиву?
Вот с чем я работаю, все работает хорошо до последнего скриншота:
Калькулятор виджетов
https://imgur.com/a/2ebpyym

Выбор конкретного виджета
https://imgur.com/a/STYeLcF

Ввод кол-во виджетов
https://imgur.com/a/B5ii32J

Результат расчета № 1 (1 лист стоит 8 виджетов)
https://imgur.com/a/CUouHAt

Задача: Результат расчета # 2
https://imgur.com/a/XJrclUY

В приведенной выше ссылке я бы предпочел заменить «62,5» в разделе «Необходимые комбинированные листы» на «93,75»
Код
server.js
'use strict';
const express = require('express');
const app = express();
let PORT = process.env.PORT || 3000;
console.log('hello1')
let operators = [
{name:'24x24 Widget', symbol:'24x24 Widget'}
];
function calculate(operator, value1, value2) {
if ( operator == '24x24 Widget' ) return value1 /8 + " sheets";
}
app.use(express.static(__dirname + '/build'));
app.use(require('body-parser').json());
app.use((req, res, next) => {
// res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Origin', 'https://mean-calculator.herokuapp.com/calculator');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
next();
});
app.listen(PORT, () => {
console.log('server started on port', PORT);
});
var array = [];
app.route('/calculator')
.get((req, res) => {
res.json({
operators
});console.log('hello in route')
array = [];
})
.post((req, res) => {
let operator = req.body.operator.name;
let value1 = req.body.value1;
let result = calculate(operator, value1);
array.push(value1/8);
console.log(array);
var sum = array.reduce(function(a, b) { return a + b; }, 0);
console.log(sum, 'this is the sum');
let doubleresult = calculate(operator, value1*2)
res.json({
result: {
operator: req.body.operator.symbol,
value1,
result,
sum
}
});
});
index.html
(Проверьте комментарий: <!-- Combining Data Here-->
)
<!DOCTYPE html>
<html data-ng-app="App">
<head>
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Open+Sans|Lora|Lato:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="main.css" charset="utf-8">
<title>Widget Calculator</title>
</head>
<body data-ng-controller="AppController as appCtrl"></body>
<h1>Solve for Material Needed for Widgets</h1>
<div class="solve">
<h2 data-ng-show="appCtrl.error" class="error">{{appCtrl.error}}</h2>
<form method="post">
<h2>Select a Widget</h2>
<select data-ng-model="operator" data-ng-options="operatorOption.name for operatorOption in appCtrl.operators">
<option value="">-- choose Widget --</option>
</select>
<h2>Select QTY</h2>
<input data-ng-model="value1" type="number" placeholder="1st Number">
<span>{{operator.symbol}}</span>
<span></span>
<button data-ng-click="appCtrl.calculate(operator, value1, value2); value1=undefined; value2=undefined; operator=undefined" type="button">Calculate</button>
</form>
</div>
<div data-ng-show="appCtrl.results.length">
<h1>Results</h1>
<div class="result">
<h2 data-ng-repeat="result in appCtrl.results">{{result.value1}} {{result.operator}} = {{result.result}}</h2>
</div>
</div>
<!-- Combining Data Here-->
<div data-ng-show="appCtrl.results.length">
<h1>Combined Sheets Needed</h1>
<div class="result combined">
<h2 data-ng-repeat="result in appCtrl.results">{{result.sum}}</h2>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.js" charset="utf-8"></script>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
app.js
var app = angular.module('App', []);
app.controller('AppController', ['$http', function($http) {
var apiRoute = 'http://localhost:3000/calculator';
var _this = this;
_this.results = [];
_this.operators = [];
$http.get(apiRoute)
.then(function(res) {
_this.operators = res.data.operators;
}, function(res) {
console.log(res);
});
_this.calculate = function(operator, value1, value2) {
_this.error = validate(operator, value1, value2);
if (!_this.error) {
$http.post(apiRoute, {operator, value1, value2})
.then(function(res) {
_this.results.push(res.data.result);
}, function(res) {
console.log(res);
});
}
}
}]);
function validate(operator, value1, value2) {
if (!operator) return 'Please select an operator.';
if ((!value1 && value1 != 0) || (!value1 && value1 != 0)) return 'Please enter two numbers.';
return null;
}