角度初学者在这里。 我正在努力为大学创建一个购物车。 我需要在文本输入中添加名称和价格,单击按钮后,项目应该添加到列表中。 问题是每当我按下按钮时都没有发生任何事情,因为控制台没有告诉我任何可能出错的事情,所以我输了。所以,这是我的代码:
<!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>
这是我的js代码:
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 = "";
}
});
答案 0 :(得分:1)
<input type = "submit" value = "Add" ng-click = "addProduct()">
需要
<input type = "button" value = "Add" ng-click = "addProduct()">
提交会将表单提交给服务器,而不是我想要的确切内容。
此外,这里的错字:
<div">
在这里(产品,而不是产品):
$scope.productos
答案 1 :(得分:1)
您已将值推送到错误的对象。 而且你需要改变很多。你的按钮点击应该需要写入
$scope.addProduct= function () {
//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 = "";
}
});