Angular beginner here. I'm trying to create a shopping cart for college. I need to add the name and price in a text input and after clicking a button the item is supposed to be added to a list. The thing is that whenever I press the button nothing happens, and I'm lost since the console doesn't tell me anything about what could be wrong. So, here's my code:
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<title>Shopping Cart</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<script src = "app.js"></script>
</head>
<body ng-controller = "myShoppingCart">
<h1>Add to cart</h1>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div">
<ul>
<li ng-repeat = "product in products">
<span>{{product.name}}</span>
<span>{{product.price}}</span>
<span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
<span>{{product.price*amount}}</span>
</li>
</ul>
</div>
</body>
</html>
And this is my js code:
var myApp = angular.module("myApp", []);
myApp.controller('myShoppingCart', function($scope) {
$scope.products = [];
function addProduct() {
$scope.productos.push({nombre:$scope.nameProduct, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}
});
You have pushed the values to wrong object . and also you need to change lot .and your button click should be need write to
$scope.addProduct= function () {
//code
}
So please copy and past my code to instead of your code
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<title>Shopping Cart</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<script src = "app.js"></script>
</head>
<body ng-controller = "myShoppingCart">
<h1>Add to cart</h1>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div>
<ul>
<li ng-repeat = "product in products">
<span>{{product.name}}</span>
<span>{{product.price}}</span>
<span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
<span>{{product.price*amount}}</span>
</li>
</ul>
</div>
</body>
</html>
var myApp = angular.module("myApp", []);
myApp.controller('myShoppingCart', function($scope) {
$scope.products = [];
$scope.addProduct= function () {
$scope.products.push({name:$scope.name, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}
});