服务更新未反映在控制器中。 AngularJS

时间:2015-04-04 03:30:02

标签: angularjs angularjs-scope

我是ProductService和ProductsController。 ProductService有ProductService.Products = [];包含所有产品信息的变量。 我在ProductsController中访问这些Products-information并存储在名为$ scope.Products = [];的变量中。

问题是其他一些服务也在使用" ProductService",以及更新"产品信息",使用" UpdateInfo"在ProductService中公开的函数。现在这些更改没有反映在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 个答案:

答案 0 :(得分:2)

您可以在控制器中的$watch上创建ProductService.Products。值更改后,您可以使用新值更新$scope.Products

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

答案 1 :(得分:-1)

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

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