I'm new to AngularJS, currently I am trying to create a spa for tracking expenses as a simple project but I have some problems with my code.
I managed to do the most of the function but I got stuck at the edit button and edit function. I am trying to make an inline edit function because I already have a form input.
Here is the html and js code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Expenses Tracker</title>
<link rel="stylesheet" href="bootstrap.min.css">
<link href="style.css" rel="stylesheet">
</head>
<body>
<nav role="navigation">
<div >
<div >
<span ><img src="logo.png" height="40" />
Simple Expenses App Tracker</span>
</div>
</div>
</nav>
<div ng-app="myList" ng-controller="myListController">
<img src="logo.png" >
<form ng-submit="newItem()" >
<input required type="number" placeholder="Amount" ng-model="amount">
<input required type="text" placeholder="Description" ng-model="description">
<input type="submit" value="Submit" >
</form>
<ul>
<li ng-repeat="item in items">
<span > {{item.amount}} den.</span> {{item.description}}
<span >
<input type="button" value="Edit" >
<input type="button" ng-click="deleteItem($index)" value="Delete" >
</span>
</li>
<br>
<li><span >{{totalPrice()}} den.</span> <span > Total Expenses</span></li>
</ul>
</div>
<script src="bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="app.js"></script>
</body>
</html>
var myApp = angular.module("myList", []);
myApp.controller("myListController", function($scope) {
$scope.items = [];
$scope.newItem = function() {
$scope.items.push({description:$scope.description, amount: $scope.amount});
$scope.description = '';
$scope.amount = 0
};
$scope.deleteItem = function(index) {
$scope.items.splice(index, 1);
}
$scope.totalPrice = function() {
var total = 0;
for(count=0; count<$scope.items.length;count ){
total = $scope.items[count].amount;
}
return total;
};
});
CodePudding user response:
You could try something like:
$scope.editItem = function(index) {
$scope.amount = $scope.items[index].amount;
$scope.description = $scope.items[index].description;
$scope.deleteItem(index);
}
I also recommend you read this book: https://www.newline.co/ng-book/modern-ng1/
Try to move away from using $scope for bindings and user components. Unless you really don't care where this project goes.