Javascript 在AngularJS中将项目添加到购物车
我是初学者。 我想为大学设计一个购物车。 我需要在文本输入中添加名称和价格,单击按钮后,该项目应添加到列表中。 问题是,每当我按下按钮时,什么都不会发生,我也会不知所措,因为控制台没有告诉我什么可能是错误的。下面是我的代码:Javascript 在AngularJS中将项目添加到购物车,javascript,angularjs,angularjs-directive,angularjs-scope,shopping-cart,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Shopping Cart,我是初学者。 我想为大学设计一个购物车。 我需要在文本输入中添加名称和价格,单击按钮后,该项目应添加到列表中。 问题是,每当我按下按钮时,什么都不会发生,我也会不知所措,因为控制台没有告诉我什么可能是错误的。下面是我的代码: <!DOCTYPE html> <html ng-app = "myApp"> <head> <title>Shopping Cart</title> <script src = "https
<!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>
您将值推送到了错误的对象。 而且你还需要改变很多。你的按钮点击应该是需要写
$scope.addProduct= function () {
//code
}
因此,请复制我的代码并将其传递给,而不是您的代码
HTML
而且
nombre
应该是name
谢谢,我把submit改为button,把form改为div,虽然没有解决我的问题。另外两个错误没有出现在我的原始代码中,因为我的程序最初不是用英语编写的,所以我不得不翻译它并删除一些与问题无关的样式。按钮单击是不调用,因为angular js需要调用$scope.functionname=function(){//code}
…看到我的答案了吗,它确实解决了我的问题。我将我的函数声明更改为您建议的,并且工作得很好。非常感谢你。
<input type = "submit" value = "Add" ng-click = "addProduct()">
<input type = "button" value = "Add" ng-click = "addProduct()">
<div">
$scope.productos
$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 = "";
}
});