2015-04-04 43 views
0

我有ProductService和ProductsController。 ProductService有ProductService.Products = [];包含所有产品信息的变量。 我在ProductsController中访问此产品信息并存储在名为$ scope.Products = [];的变量中。服务更新没有反映在控制器中。 AngularJS

问题是一些其他服务也使用“ProductService”,并使用ProductService中公开的“UpdateInfo”函数更新“Products Info”。现在这些更改不会反映在ProductsController变量$ scope.Products = [] ;.

这是我的代码。

sampleApp.factory('ProductService', ['$http', '$q', function ($http, $q){ 
    var req = { 
     method: 'POST', 
     url: 'ProductData.txt', 
     //url: 'http://localhost/cgi-bin/superCategory.pl', 
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//, 
     //data: { action: 'GET' } 
    }; 
    var ProductService = {}; 
    ProductService.Products = []; 
    return { 
     GetProducts: function() { 
      var defer = $q.defer(); 
      $http(req).then(function(response) { 
       ProductService.Products = response.data; 
       defer.resolve(ProductService.Products); 
      }, function(error) { 
       defer.reject("Some error"); 
      }); 
      return defer.promise; 
     }, 

     UpdateInfo: function (ProductID, VariantID) { 

      for (i in ProductService.Products) { 
       if (ProductService.Products[i].ProductID == ProductID) { 
        for (j in ProductService.Products[i].Variants) { 
         if (ProductService.Products[i].Variants[j].VariantID == VariantID) { 
          ProductService.Products[i].Variants[j].InCart = 1; /* Updating Info Here, But its not reflecting */ 
          break; 
         } 
        } 
        break; 
       } 
      } 
     } 
    }; 
}]); 


sampleApp.controller('ProductsController', function ($scope, $routeParams, ProductService, ShoppingCartService) { 

    $scope.Products = []; 

    $scope.GetProducts = function() { 
     ProductService.GetProducts().then 
     (
      function(response) { 
       $scope.Products = response; 
      }, 
      function(error) { 
       alert ('error worng'); 
      } 
     ); 
    }; 

    $scope.GetProducts(); 



}); 

有人可以帮我解决这个问题吗?

回答

2

您可以在您的控制器上创建一个$watchProductService.Products。当值更改时,可以使用新值更新$scope.Products

$scope.$watch('ProductService.Products', function() { 
    $scope.Products = ProductService.Products; 
}); 
+0

感谢您的回复。还有一件事,每次我的代码路由到“ProductsController”时,它都会调用$ scope.GetProducts();它在内部调用ProductService和http服务,所以每次发出http请求。它将修改后的ProductInfo更新为新的响应。如何避免这种情况? – 2015-04-04 04:04:18

+0

服务被注入,从而共享资源。想象它有两个变量指向C#,VB或类似的引用类型。如果你改变它的一个地方,它到处改变。 – Yatrix 2015-04-04 04:08:28

-1

尝试将ProductsService.Products分配给$ scope.products。

$scope.GetProducts = function() { 
      ProductService.GetProducts().then 
      (
       function(response) { 
        $scope.Products = ProductService.Products; 
       }, 
       function(error) { 
        alert ('error worng'); 
       } 
      ); 
     }; 
相关问题