从工厂请求数据并将数据返回到同一工厂以在控制器之间共享

时间:2014-08-11 02:57:04

标签: javascript angularjs caching dependency-injection factory

问题:

如何在同一工厂存储和请求数据?

使用AngularJS,我创建了一个名为factory

Products
app.factory('Products', function($http, ENV){
    var Products = {};

    Products.details = 
    {
        //grabs the most current endpoint and creates a session of that data
        current: {},
        getProduct: function($scope, productId) {
            return $http.get(ENV.apiEndpoint + '/v2/listings/' + productId + '.json')
            .success(function(data){

              return data;
            })
            .error(function(data, status){
              console.log('error:' + status);
            });
        }

    }

    return Products;
});

此产品数据来自名为MainCtrl的父控制器:

 .controller('MainCtrl', function($scope, Products) {
   $scope.product = Product.details.current;
   var handleProductSuccess = function (data) {

     //stores the data for the current controller but also sends the data back to factory         
     $scope.product = data;
   };
   //on click of a product from view
   Products.details.getProduct($scope, $scope.productId).success(handleProductSuccess);
 }

成功请求来自api的数据后,我想将其保存回Product.details.current对象的工厂。

这里有一些例子返回了json:

{
"_id": "53e82f1d702724156ca806b0",
"index": 0,
"guid": "dd3b8081-867e-4908-90e7-70f5d6f32203",
"isActive": false,
"balance": "$2,233.42",
"picture": "http://placehold.it/32x32",
"age": 33,
"eyeColor": "green",
"name": "Deirdre Floyd",
"gender": "female",
"company": "KAGGLE",
"email": "deirdrefloyd@kaggle.com",
"phone": "+1 (842) 451-3828",
"address": "701 Lois Avenue, Rew, California, 4370"
}

最后,Product.details.current基本上是一个'会话(?)'数据集。这些数据可以在应用程序的许多范围,指令和状态之间传递。通过创建一个空间来请求数据并存储要操作的数据会话,我认为这是一种非常小的方法。不幸的是,我的逻辑/语法不允许我这样做。

你能帮助我使用正确的逻辑和语法吗?

1 个答案:

答案 0 :(得分:1)

您可以直接从getProducts函数更新Pr​​oducts.details.current。如果可以从应用中的不同位置调用getProduct,并且希望在控制器中保持信息同步,则可以使用$ watch。

app
    .factory('Products', function($http, ENV){
        var Products = {};

        Products.details =
        {
            //grabs the most current endpoint and creates a session of that data
            current: {},
            getProduct: function($scope, productId) {
                return $http.get(ENV.apiEndpoint + '/v2/listings/' + productId + '.json')
                    .success(function(data){
                        Products.details.current = data; // Update 
                        return data;
                    })
                    .error(function(data, status){
                        console.log('error:' + status);
                    });
            }

        };

        return Products;
    })

    .controller('MainCtrl', function($scope, Products) {
        $scope.product = Products.details.current;
        var handleProductSuccess = function (data) { // (not required if you use the watch below)

            // stores the data for the current controller

            $scope.product = data;
        };
        //on click of a product from view
        Products.details.getProduct($scope, $scope.productId)
            .success(handleProductSuccess);


        // If another scope can modify Products.details.current and you want to watch for it:
        $scope.$watch(
            function () { return Products.details.current;},
            function (newVal) { $scope.product = newVal; },
            true
        );
    });