因此,我有一个productList和用于存储产品的购物车,当我将产品添加到购物车(localStorage)时,产品计数必须异步刷新,但仅在刷新页面时才刷新(这与goodsInCart有关)。也许需要添加EventListener?请告诉我我错了。

products.html

<div ng-controller="ProductController">
    <div class="container">
        <h1 class="page-header">Product List</h1>
         <div class="small-cart">
            <a href="#!/cart">
              <span class="amount">{{goodsInCart}}</span>
              <img class="cart" src="./images/cart_2.png">
            </a>
          </div>
         <div class="row">
            <div class="item col-sm-6 col-md-4 col-lg-3" ng-repeat="product in products">
                <h3>{{product.title}}</h3>
                <img class="product-photo" src="{{product.photoURL}}" alt="">
                <p>{{product.price}} UAH</p>
                <button class="btn btn-cart" ng-click="addToCart(product)">Add to cart</button>
            </div>
        </div>
     </div>
</div>


ProductService.js

testApp.factory('CartProduct', function(localStorageService) {
  var cartProducts = [];
  var goodsInCart = 0;

  function init() {
    checkCartChanged();
    if (localStorageService.get('cart-products')!=null) {
      cartProducts = localStorageService.get('cart-products');
      calcGoodsInCart();
    }
  }

  init();

  function getAll() {
    return cartProducts;
  }

  function addToCart(product) {
      cartProducts.push({product : product,amount : 1});
      refresh();
    }

  function store(key,value) {
     localStorageService.set(key, value);
  }

  function calcGoodsInCart() {
     var temp = 0;
     temp = cartProducts.length;
     goodsInCart = temp;
     return goodsInCart;
  }

  function getStorageItem(key) {
    for (var i = 0; i < localStorageService.length(); i++) {
        return localStorageService.get(key);
    }
    return null;
  }


  function checkCartChanged() {
    const storedGoods = getStorageItem('goods');
    cartProducts = storedGoods ? storedGoods : [];
    calcGoodsInCart();
  }

  function refresh () {
    store("goods",cartProducts);
    calcGoodsInCart();
  }

  function deleteAllProducts() {
    this.localStorageService.clear('goods');
  }

  function findCartItem(product){
    for(let i =0; i < cartProducts.length;i++){
      if (product.id == cartProducts[i].product.id) {
        return i;
      }
    return -1;
    }
  }

  function deleteProduct(product){
    let index = findCartItem(product);
    if (index < 0) {
      return;
    }
    cartProducts.splice(index, 1);
    refresh();
  }

  function deleteAllProducts() {
    localStorageService.clear('goods');
  }

  return {
    addToCart: addToCart,
    getAll: getAll,
    calcGoodsInCart:calcGoodsInCart,
    getStorageItem:getStorageItem,
    deleteProduct:deleteProduct,

    goodsInCart:goodsInCart
  };
});


ProductController.js

testApp.controller('ProductController',function ProductController($scope,$http,CartProduct) {
    $scope.products = [
       { id:1, title: 'Margarita', photoURL:'...',price:260},
       { id:2, title: 'Margarita', photoURL:'...', price:240},
       { id:3, title: 'Margarita', photoURL:'...', price:200},
       { id:4, title: 'Margarita', photoURL:'...', price:190}
    ];

    $scope.addToCart = function (product) {
        CartProduct.addToCart(product);
    }

    $scope.goodsInCart = CartProduct.goodsInCart;

});

最佳答案

您的方法有两个问题,第一个是您只在控制器的goodsInCart行中保存$scope.goodsInCart = CartProduct.goodsInCart;的第一个值。

第二个是您只公开值而不是引用。

解决方案是将goodsInCart包装在一个对象内并提供其引用。

testApp.factory('CartProduct', function(localStorageService) {
  var cartProducts = [];
  var sharedObj = {
    goodsInCart: 0
  }

  ...

  function calcGoodsInCart() {
    var temp = 0;
    temp = cartProducts.length;
    sharedObj.goodsInCart = temp;
    return temp;
  }

  ...

  return {
    addToCart: addToCart,
    getAll: getAll,
    calcGoodsInCart:calcGoodsInCart,
    getStorageItem:getStorageItem,
    deleteProduct:deleteProduct,

    sharedObj:sharedObj
  };


注意:尝试共享对象时要小心,如果在工厂内部更改sharedObj的引用,则使用该对象的任何控制器都会丢失该引用。这就是为什么您只应修改共享obj的属性的原因。

然后,您可以像下面这样在控制器中使用提供的对象:

$scope.sharedObj = CartProduct.sharedObj;


希望能帮助到你!

08-17 07:07