简体   繁体   中英

AngularJs promise not updating shared Shopping Cart

I'm not sure why this customer data doesn't update the shoppingCart.html template, this function is part of a shared model class returned by a factory.

the $http is injected but the model class can't manage to update itself inside the promise result. So the template is finally updated. What would be the best way to do that?

http://plnkr.co/edit/ro6FTa5AbhnzrMsnWIyi?p=preview

    shoppingCart.prototype.fillCustomerInformation = function()
    {
        var customerDeferred = this.$q.defer();
        var customerApi = customerDeferred.promise;

        this.$http.get('/customer.json').then(function (result) {
            customerDeferred.resolve(result.data);
            console.log(result.data);
            this.customer.firstName = result.data.firstName;
            this.saveItems()
        });

     }

The problem is, that this refers to the success ajax handler. You can do this:

shoppingCart.prototype.fillCustomerInformation = function()
    {
        var customerDeferred = this.$q.defer();
        var customerApi = customerDeferred.promise;
        var that = this;

        this.$http.get('/customer.json').then(function (result) {
            customerDeferred.resolve(result.data);
            console.log(result.data);
            that.customer.firstName = result.data.firstName;
            that.saveItems()
        });

     }

Well for a start you have firstName spelt wrong in result.data.firtName instead of result.data.firstName

Secondly there are many ways to bind service members to scope variables but what i found was the best way of doing that is to do stuff like

$scope.$watch(
  function () {
    return DataService.cart;
  },
  function (newVal, oldVal) {
    // do your stuff to manage updates here
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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