ng-model使用ng-change未通过ng-click更新

时间:2016-04-18 16:08:51

标签: angularjs

已更新

我认为

ng-init="currentQuantity=item.quantity"

只是阻止 ng-model currentQuantity 更新为下一个递增的值。在下面的示例中是否有任何解决方法?

例如,我可以通过索引来定位 currentQuantity模型,这样我就知道我正在改变哪种模式而不是一次改变所有模型?


我目前在使用AngularJS时遇到问题。通过下面的代码我将产品添加到购物车阵列:

QuantityChanged(product, currentQuantity);

接下来,我在此输入字段旁边有一个+按钮,只是将+1产品数量添加到购物车。

<button class="plus-button" ng-click="addToCart(product);">+</button>

我的ng-model =“currentQuantity”只会在使用QuantityChanged(product,currentQuantity)时更新,但在我使用ng-click =“addToCart(product)”函数时不会更新。

如果我查看我的本地存储,我会看到购物车的数量已成功更新,但当我查看ng-model的当前输入文本字段值时:currentQuantity我看到没有任何更改。当我刷新时,我会在输入字段中看到正确的值。我错过了一些明显的东西吗?

查看:

<span ng-repeat="item in cart">
      <span ng-if="item.id === product.id">
            <input type="text" ng-change="QuantityChanged(product, currentQuantity);" ng-model="currentQuantity" ng-init="currentQuantity=item.quantity" class="product-aantal"  />
      </span>
</span>

<button class="plus-button" ng-click="addToCart(product);">+</button>

某些控制器代码(如有必要):

$scope.QuantityChanged = function (product, quantity) {

        quantity = parseFloat(quantity, 6);

        $scope.cart.forEach(function (item) {
            if (item.id === product.id) {

                if(item.quantity < quantity){
                    $scope.productCounter = $scope.productCounter + (quantity - item.quantity);
                }
                if(item.quantity > quantity){
                    $scope.productCounter = $scope.productCounter - (item.quantity - quantity);
                }

                item.quantity = quantity;
                item.totalprice = parseFloat(item.price,6) * quantity;
            }
        });

        this.saveProducts($scope.cart);
        this.saveProductCounter($scope.productCounter);

    };


$scope.addToCart = function (product) {

        var found = false;
        $scope.cart.forEach(function (item) {
            if (item.id === product.id) {
                item.quantity++;
                $scope.productCounter++;
                item.totalprice += parseFloat(item.price,6);
                found = true;
            }

        });
        if (!found) {
            $scope.cart.push(angular.extend({quantity: 1, totalprice: parseFloat(product.price,6) }, product));
            $scope.productCounter += 1;
        }


        this.saveProducts($scope.cart);
        this.saveProductCounter($scope.productCounter);

    };

1 个答案:

答案 0 :(得分:1)

它与ng-repeat的范围有关。

将currentQuantity更改为current.quantity,并且addToCart内部也会操纵该值。

Fiddle

if (item.id === product.id) {
    item.quantity++;
    $scope.current.quantity++;
    $scope.productCounter++;
    item.totalprice += parseFloat(item.price,6);
    found = true;
}

我必须说你的逻辑很难理解,但这解决了这个问题。