I am writing an application for calculating the budget, how to implement the output of the sum of the numbers entered?

function TodoCtrl($scope){ var sums = $scope.sums = []; $scope.sum = '200'; $scope.addSu = function(sum){ sums.push(sum); }; $scope.removeSum = function(index){ sum.splice(index,1); }; } 
 <!DOCTYPE html> <html> <head> <script src="http://code.angularjs.org/1.1.4/angular.min.js"></script> <script src="todo.js"></script> </head> <body> <div ng-app> <div ng-controller="TodoCtrl"> <h2>Сегодня я потратил: {{sum}} руб.</h2> <input type = 'text' ng-model = "sum" size = "40" /> <button ng-click = "addSu(sum)">Добавить</button> <ul> <li ng-repeat = "sum in sums track by $index"> <span ng-bind="$parent.$eval(sum)"></span> <span>руб</span> </li> </ul> </div> </div> </body> </html> 

  • and you took this code somewhere or did you write it yourself? - Grundy
  • Half of me, half of the site angular.ru - spmpl
  • try not to use functions to output values ​​of type $ parent. $ eval (sum) and generally do not usually use eval outside of directives - Grundy
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

To display the total amount, you must first calculate it. To do this, you can create a variable in which when adding a number will be added, when deleting - to subtract.

I want to note that the example in question uses the old version of angular, and the above code will not work as it is for newer versions. The answer uses angular version 1.4.7

 angular.module('app', []) .controller('ctrl', function($scope) { var sums = $scope.sums = []; $scope.sum = '200'; $scope.total = 0; // итого $scope.addSu = function(sum) { $scope.total += +sum; // переводим sum в число и добавляем к total sums.push(+sum); // Добавляем в список }; $scope.removeSum = function(index) { $scope.total -= sums.splice(index, 1);//удаляем из списка и вычитаем из total }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> <div ng-app="app"> <div ng-controller="ctrl"> <h2>Сегодня я потратил: {{total}} руб.</h2> <input type='text' ng-model="sum" size="40" /> <button ng-click="addSu(sum)">Добавить</button> <ul> <li ng-repeat="sum in sums track by $index"> <span ng-bind="sum"></span> <span>руб</span> <span ng-click="removeSum($index)">Удалить</span> </li> </ul> </div> </div> 

  • Thank! Everything is working. What kind of error in the console? WARNING: Tried to load angular more than once. Uncaught TypeError: window.angular. $$ csp is not a function - spmpl
  • @spmpl, is this a bug in your code or snippet code? most likely you copied the html completely, while capturing the <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> line, connecting the angular, but did not remove the same from the head tag - Grundy
  • Corrected. Thank! - spmpl