在AngularJS中,购物车和产品列表之间的数据流可以通过使用服务和双向数据绑定来实现。以下是一个解决方案的示例代码:
首先,创建一个名为ProductService
的服务,用于管理产品列表和购物车数据:
angular.module('myApp').service('ProductService', function() {
var products = [
{id: 1, name: 'Product 1', price: 10},
{id: 2, name: 'Product 2', price: 20},
{id: 3, name: 'Product 3', price: 30},
// ...
];
var cart = [];
return {
getProducts: function() {
return products;
},
getCart: function() {
return cart;
},
addToCart: function(product) {
cart.push(product);
},
removeFromCart: function(product) {
var index = cart.indexOf(product);
if (index !== -1) {
cart.splice(index, 1);
}
}
};
});
接下来,在控制器中使用ProductService
服务来管理数据流:
angular.module('myApp').controller('ProductController', function($scope, ProductService) {
$scope.products = ProductService.getProducts();
$scope.cart = ProductService.getCart();
$scope.addToCart = function(product) {
ProductService.addToCart(product);
};
$scope.removeFromCart = function(product) {
ProductService.removeFromCart(product);
};
});
然后,在视图中使用双向数据绑定来显示产品列表和购物车:
产品列表
-
{{product.name}} - {{product.price}}
购物车
-
{{product.name}} - {{product.price}}
这样,当用户点击“添加到购物车”按钮时,addToCart
函数将被调用,将产品添加到购物车中。当用户点击“从购物车移除”按钮时,removeFromCart
函数将被调用,将产品从购物车中移除。通过双向数据绑定,产品列表和购物车将自动更新以反映最新的数据。