gpt4 book ai didi

javascript - 在 AngularJS 中将商品添加到购物车

转载 作者:行者123 更新时间:2023-12-02 16:22:58 25 4
gpt4 key购买 nike

这里是 Angular 初学者。我正在尝试为大学创建一个购物车。我需要在文本输入中添加名称和价格,单击按钮后,该项目应该添加到列表中。问题是,每当我按下按钮时,什么也没有发生,而且我迷失了,因为控制台没有告诉我任何可能出现问题的信息。所以,这是我的代码:

<!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 = "";
}

});

最佳答案

您已将值推送到错误的对象。而且您还需要更改批处理。您的按钮单击应该需要写入

 $scope.addProduct= function () {
//code
}

所以请复制并粘贴我的代码而不是您的代码

HTML

<!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 = [];

$scope.addProduct= function () {

$scope.products.push({name:$scope.name, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}

});

关于javascript - 在 AngularJS 中将商品添加到购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28939784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com