简体   繁体   English

发布后更新angularJS中的$ scope属性

[英]Updating $scope attributes in angularJS after post

First of all, yes i did look at other answers but they didn't do the trick for me. 首先,是的,我确实看过其他答案,但他们并没有为我解决问题。

I'm currently working on an angularJS based shopping application. 我目前正在angularJS基于angularJS的购物应用程序。 After building the cart, creating the neccesary functions and building the view i would like to optimize the "cart" by creating an "no page refresh", add_to_cart function. 构建购物车,创建必要的功能并构建视图之后,我想通过创建“无页面刷新” add_to_cart函数来优化“购物车”。 So after some struggeling with functions like $scope.push and an init() load the cart function i got a bit stuck. 因此,在使用诸如$scope.pushinit()这样的函数进行了一些努力之后,我陷入了困境。 The cart is build by the following code: 购物车是通过以下代码构建的:

Get the cart: 取得购物车:

$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;
    });
};

Add a product: 添加产品:

$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);
};

By clicking on a button all the data is obtained from the view and passed to the addToCart() function. 通过单击按钮,可以从视图中获取所有数据,并将其传递给addToCart()函数。 I've checked everything and the data gets inserted. 我检查了所有内容,并插入了数据。 After a hard page refresh the new product is added to the cart. 硬页刷新后,新产品将添加到购物车。 But i would like to remove the "hard page refresh" and use something like i've tried above: $scope.cartItems.push(request); 但是我想删除“硬页刷新”并使用类似我上面尝试过的东西: $scope.cartItems.push(request); .

Update 更新

So after some tips from the comments i've created a service for the cart. 因此,从评论中获得一些提示后,我为购物车创建了一项服务。 Take a look at the updated code: 看一下更新的代码:

cartService 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 and function add 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();
        });
    };
});

So everything works fine, i can even see in the network tab that the new getCart.php is obtained with the new data. 因此,一切正常,我什至可以在网络标签中看到使用新数据获取新的getCart.php Sadly still my $scope and view isn't updated. 可悲的是,我的$scope和视图仍未更新。

Update 2 更新2

So i've taken a look at the example and i've tried some things for myself. 因此,我看了一个例子,并为自己尝试了一些东西。 After some tries i came to a very weird conclusion: Using an ng-click refreshData action refreshes the data through the following function: 经过一番尝试,我得出了一个非常奇怪的结论:使用ng-click refreshData操作通过以下函数刷新数据:

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

but calling this function directly like the example in the first answer (jsFiddle) => fiddle won't refresh the view and $scope 但是像第一个答案(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();
    })
};

If you have any questions please let me know in the comments 如有任何疑问,请在评论中让我知道

PS: creating a JSfiddle would put me back with a lot of time since all the data is obtained through the Prestashop webservice PS:创建JSfiddle会让我花很多时间,因为所有数据都是通过Prestashop Web服务获取的

As always, Thanks in advance! 一如既往,预先感谢!

Seems like you are using wrong approach. 似乎您使用的是错误的方法。 All http calls should be made from services, not from controllers/components. 所有http调用都应来自服务,而不是控制器/组件。 Try to create a service for this. 尝试为此创建服务。 Don't forget to inject the service in your controller. 不要忘记将服务注入到控制器中。 So after all there will be something like this 所以毕竟会有这样的事情

for example: 例如:

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

register service according to the docs and add method 根据docs和add方法注册服务

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM