【问题标题】:Updating $scope attributes in angularJS after post发布后在 angularJS 中更新 $scope 属性
【发布时间】:2018-07-02 02:47:40
【问题描述】:

首先,是的,我确实看过其他答案,但他们并没有为我解决问题。

我目前正在开发一个基于angularJS 的购物应用程序。在构建购物车、创建必要的功能并构建视图之后,我想通过创建“无页面刷新”add_to_cart 函数来优化“购物车”。因此,在使用$scope.pushinit() 之类的功能进行了一些挣扎之后,加载购物车功能我有点卡住了。购物车由以下代码构建:

获取购物车:

$scope.getCartItems = function() {
    // Get the cart
    $http.get('config/cart/getCart.php', {cache: false}).then(function (response) {
        $scope.cartItems = [];
        $scope.cartItems = response.data.cartItems;
        $scope.totalCartItems = [];
        $scope.totalCartItems = response.data;
        $scope.selectedCustomer = [];
        $scope.selectedCustomer = response.data;
    });
};

添加产品:

$scope.addToCart = function(product, stock_available) {
    var product_id = product.id;
    var product_name = product.name.language;
    var product_price = $('span[name="combinationTotalPrice' + stock_available.id + '"]').text();
    var product_size = $('span[name="product_attributes' + stock_available.id + '"]').text();
    var product_quantity = product.quantity;
    var product_id_attribute = stock_available.id_product_attribute;

    console.log(product_id_attribute);

    var request = $http({
        method: "post",
        url: "config/cart/getCart.php?action=addToCart",
        data: {
            product_id: product_id,
            product_name: product_name,
            product_price: product_price,
            product_size: product_size,
            product_quantity: product_quantity,
            product_id_attribute: product_id_attribute
        },
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    $scope.cartItems.push(request);
};

通过单击按钮,所有数据都从视图中获取并传递给addToCart() 函数。我已经检查了所有内容并插入了数据。硬页面刷新后,新产品将添加到购物车中。但我想删除“硬页面刷新”并使用我上面尝试过的东西:$scope.cartItems.push(request);

更新

因此,根据 cmets 的一些提示,我为购物车创建了一项服务。看看更新后的代码:

cartService

myApp.service('cartService', ['$http',function ($http, $scope) {
    return {
        getCartItems: function() {
            return $http.get('config/cart/getCart.php', {cache: false})
        }
        // any other methods for http calls;
    }
}]);

cartController 和函数添加

myApp.controller('CartController', function($http, $scope, cartService) {
    $scope.getTheCart = function() {
        cartService.getCartItems()
            .then(function(response) {
                $scope.cartItems = response.data.cartItems;
                $scope.totalCartItems = response.data;
                $scope.selectedCustomer = response.data;
            })
    };

$scope.addToCart = function(product, stock_available) {
        var product_id = product.id;
        var product_name = product.name.language;
        var product_price = $('span[name="combinationTotalPrice' + stock_available.id + '"]').text();
        var product_size = $('span[name="product_attributes' + stock_available.id + '"]').text();
        var product_quantity = product.quantity;
        var product_id_attribute = stock_available.id_product_attribute;

        console.log(product_id_attribute);

        var request = $http({
            method: "post",
            url: "config/cart/getCart.php?action=addToCart",
            data: {
                product_id: product_id,
                product_name: product_name,
                product_price: product_price,
                product_size: product_size,
                product_quantity: product_quantity,
                product_id_attribute: product_id_attribute
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(function() {
            $scope.getTheCart();
        });
    };
});

所以一切正常,我什至可以在网络选项卡中看到新的getCart.php 是使用新数据获得的。可悲的是我的$scope 仍然没有更新。

更新 2

所以我看了一下这个例子,并为自己尝试了一些东西。经过一些尝试,我得出了一个非常奇怪的结论:使用 ng-click refreshData 操作通过以下函数刷新数据:

$scope.refreshData = function() {
    cartService.refreshData()
        .then(function(response) {
            $scope.cartItems = response.data.cartItems;
            $scope.totalCartItems = response.data;
            $scope.selectedCustomer = response.data;
        })
};

但是像第一个答案中的示例一样直接调用此函数 (jsFiddle) => fiddle 不会刷新视图和 $scope

$scope.addToCart = function(product, stock_available) {
    return cartService.addToCart(product, stock_available)
        .then(function(response) {
        console.log(response);
            $scope.cartItems = response.data.cartItems;
            $scope.totalCartItems = response.data;
            $scope.selectedCustomer = response.data;
        // call the get() function
        $scope.refreshData();
    })
};

如果您有任何问题,请在 cmets 中告诉我

PS:创建一个 JSfiddle 会让我花很多时间回来,因为所有数据都是通过 Prestashop webservice 获得的

一如既往,提前致谢!

【问题讨论】:

  • $http 返回一个 Promise。如果你想从中获取数据,你需要解决它:$http(...).then((res)=>{$scope.cartItems.push(res.data);});
  • @AlekseySolovey $http({...}).then(function(response){ $scope.cartItems.push(response.data.cartItems); }); 返回:$scope.cartItems.push is not a function
  • 是在 $scope.addToCart(...) 之前调用了 $scope.getCartItems() 吗?因为它初始化了数组$scope.cartItems = [];
  • @AlekseySolovey 是的,它在 $scope.addToCart 之前被调用

标签: javascript php angularjs json post


【解决方案1】:

似乎您使用了错误的方法。所有 http 调用都应该来自服务,而不是来自控制器/组件。 尝试为此创建服务。 不要忘记在控制器中注入服务。 所以毕竟会有这样的东西

例如:

$scope.cartItems = [];
$scope.getCartItems = function() {
cartService.getCartItems()
  .then(response => {
    $scope.cartItems  = response.data; // or response
  })
}

根据文档注册服务并添加方法

return {
  getCartItems: function() {
    return $http.get('config/cart/getCart.php', {cache: false})
  },
  // any other methods for http calls;
}

【讨论】:

  • 你能分享一个完整的例子吗?
  • 感谢您提供完整的示例。所以我创建了服务并将其添加到我的控制器中。一切正常。这是一项很棒的技术。遗憾的是 $scope 仍然没有更新。请您看一下问题的“更新”部分吗?
  • 更新已添加
  • 好吧,我已经包含了小提琴示例,并进行了一些名称调整。控制台返回带有 ng-click 添加数据的新购物车。在我使用硬刷新之前,视图仍然没有更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多