简体   繁体   中英

Requesting data from factory and returning data back to same factory for sharing between controllers

QUESTION:

How do I store and request data in the same factory?

Using AngularJS, I have created a factory called 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;
});

This product data is being pull from a parent controller called 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);
 }

Upon successful request of data from api I would like to save it back to the factory in the Product.details.current object.

Here's some example returned 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"
}

In the end this Product.details.current is essentially a 'session(?)' set of data. This data could be be passed between many scopes, directives and states of the app. I see this being a very minimal method by creating one space to do requesting of the data and storing a session of data to be manipulated. Unfortunately my logic/syntax isnt allowing me to do this properly.

Could you help me with the proper logic as well as syntax?

You can update Products.details.current directly from your getProducts function. If getProduct can be called from different places in your app and you want to keep the info in sync within your controller, you can use a $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
        );
    });

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