【问题标题】:Data Binding using service not working for Angular JS使用服务的数据绑定不适用于 Angular JS
【发布时间】:2017-04-06 02:04:00
【问题描述】:

我正在尝试使用 Angular JS 服务创建一个购物车。此服务称为 UserCart。 UserCart 服务包含两个变量,一个用于维护购物车的总价值,另一个用于存储添加到购物车中的商品。它还包含两个用于在购物车中添加或删除商品的功能。

UserCart 服务返回一个对象,该对象具有两个功能(添加/删除产品)和购物车总价值。

在视图中(最后的 html 代码),每个产品(当前是衬衫和葡萄酒)都有一个“添加到购物车”按钮,单击该按钮时应调用 ProductController 的函数“addToCart”,然后更新 UserCart 的 total_cart_val (正如我从控制台日志中确认的那样)。但是,该值并未反映在 HTML 中。

代码有什么明显的问题吗?

UserCart.js 如下:

(function() {
    // Get reference to the app
    var app = angular.module("jargoViewer");

    // Create the factory that share the User Cart with various controllers
    app.factory('UserCart', function(){
        var cart_items = [];
        var total_cart_val = 0;
        
        var addProductInCart = function(prodID, prodCostPerUnit, prodQuantity) {
            if((prodID in cart_items)) {
                // true if "prodID" exist in cart_items
                // Add the new prodID key element now
                prodObj = cart_items[prodID];
                prodObj.Quantity = prodObj.Quantity + prodQuantity;
            } else {
                // A product with same key already exists
                cart_items[prodID] = {
                    'Quantity' : prodQuantity,
                    'CostPerUnit' : prodCostPerUnit
                };
            }
            // Add the total newly added products cost to Total Cart Value
            total_cart_val += prodCostPerUnit * prodQuantity;
        }
        
        var removeProductInCart = function(prodID, prodQuantity) {
            if((prodID in cart_items)) {
                // true if "prodID" exist in cart_items
                // Add the new prodID key element now
                prodObj = cart_items[prodID];
                existingQuantity = prodObj.Quantity;
                if(prodQuantity > existingQuantity) {
                   alert('No more of this item exists in the cart!');
                } else {
                    prodObj.Quantity = prodObj.Quantity - prodQuantity;
                    // Add the total newly added products cost to Total Cart Value
                    total_cart_val -= prodCostPerUnit * prodQuantity;
                    if(prodObj.Quantity < 1) {
                        // No more of this product left in cart, remove from cart list
                        cart_items.splice(prodID, 1);
                    }
                }
            } else {
                // Error
                alert('No more of this item exists in the cart!');
            }
        }
        
        // Return the Interface of UserCart
        return { 
            // products_in_cart: cart_items,
            cart : {
                cart_val : total_cart_val
            },
            addProdInCart : addProductInCart,
            delProdInCart : removeProductInCart
        };
    });
}());

我的 ProductController.js 是这样的

(function() {

    var app = angular.module("jargoViewer");

    //var ProductController = function($scope) {
    var ProductController = function($scope, UserCart) {

        $scope.addToCart = function(prodID, costPerUnit, quantity) {
            UserCart.addProdInCart(prodID, costPerUnit, quantity);
        }
        
        $scope.products = [
            {
                'title' :   'First Product',
                'id'    :   100001,
                'img'   : 'product/shirt.jpg',
                'cost'  : 899,
                'sizes' : [
                    {
                        'label' :'Small'
                    },
                    {
                        'label' :'Medium'
                    }
                ]
            },
            {
                'title' : 'Second Product',
                'img'   : 'product/wine.png',
                'id'    : 100002,
                'cost'  : 3150,
                'sizes' : [
                    {
                        'label' :'Small'
                    },
                    {
                        'label' :'Large'
                    }
                ]
            }
        ];
        
        $scope.userCart = UserCart.cart;
    };
    
    app.controller("ProductController", ProductController);

}());

我的观点如下。

    <section class="big-product">
        <div class="container">
            <div class="row top30" ng-repeat="prod in products">
                <span>&nbsp</span>
                <div>
                    <div class="col-sm-4 product">
                        <!--<img src="product/shirt.jpg" alt="t-shirt" class="img-responsive">-->
                        <img src="{{prod.img}}" alt="t-shirt" class="img-responsive">
                    </div>
                    <div class="col-sm-8 info">
                        <div class="info-wrapper"  >
                            <h2>{{prod.title}}</h2>
                            <p class="lead">
                                {{prod.desc}}
                            </p>

                            <ul class="list-inline">
                                <li>
                                        <div class="dropdown">
                                            <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">
                                                Size
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
                                                  <li role="presentation" ng-repeat="prop in prod.sizes"><a role="menuitem" tabindex="-1" href="#">{{prop.label}}</a></li>
                                                  <!--<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Medium</a></li>
                                                  <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Large</a></li>-->
                                            </ul>
                                        </div>
                                </li>
                                <li>
                                        <div class="dropdown">
                                            <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">
                                                Quantity
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
                                                  <li role="presentation"><a role="menuitem" tabindex="-1" href="#">1</a></li>
                                                  <li role="presentation"><a role="menuitem" tabindex="-1" href="#">2</a></li>
                                                  <li role="presentation"><a role="menuitem" tabindex="-1" href="#">3</a></li>
                                            </ul>
                                        </div>

                                </li>
                                <li class="currency">
                                    {{prod.cost}}
                                </li>
                                <li class="Total Cart Value">
                                    {{userCart.cart_val}}
                                </li>
                            </ul>
                        </div>
                        <a class="btn btn-success btn-unique" ng-click = "addToCart(prod.id, prod.cost, 1)">Add to Cart<i class="icon-cart-1"></i></a>
                    </div>
                </div>
                <span>&nbsp</span>
            </div>
        </div>
    </section>

【问题讨论】:

    标签: javascript angularjs angular-services


    【解决方案1】:

    在此处发布我的 IRC 答案:

    total_cart_val 是一个原语,因此当您将其分配给cart.cart_val 时,您分配的是值而不是对变量的引用。由于您更新的是 total_cart_val 变量而不是 cart.cart_val 属性,因此更改不会反映在导出的购物车对象中,因此不会反映在您的视图中。

    【讨论】:

    • 工作就像一个魅力蒂亚特!谢谢
    【解决方案2】:

    尝试将$scope.userCart = UserCart.cart; 更改为:

    $scope.userCart= function() {
      return UserCart.cart;
    };
    

    【讨论】:

    • 好的,但是为什么需要这个呢?为什么我正在做的事情不起作用?它真的令人费解所有这些约定。链接将不胜感激
    • 更改无效。如果可以的话,你能提供一个可行的代码吗?
    猜你喜欢
    • 2016-10-19
    • 2019-08-04
    • 2020-01-02
    • 2018-08-23
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多