Pregunta

I found that the document from angularjs website says I could do something in my factory like this:

 var speicialProducts = [];

 factory.getFeatureProducts = function () {
    if ($.isEmptyObject(specialProducts)) {
        specialProducts = $resource('index.php/products/featureProducts').query().$promise.then(function(data){
            return data;
            // return data.content;
        });
    }
    return specialProducts;
}

and then in my controller I do:

$scope.specialProducts = specialProductFactory.getFeatureProducts();

But somehow the angularjs doesn't fill up the scope model when the data is been correctly returned.

I did try to do:

var speicialProducts = [];

 factory.getFeatureProducts = function () {
    if ($.isEmptyObject(specialProducts)) {
        specialProducts = $resource('index.php/products/featureProducts').query();
    }
    return specialProducts;
} 

This is working, but I want to do something to assign part of the returned data to specialProducts but not the entire returned data (like what I did in the comment part in the first code example return data.content). So any ideas I could make this works?

if there are some jsfiddle examples that will be great. Thanks

¿Fue útil?

Solución

Try this

 if ($.isEmptyObject(specialProducts)) {
        $resource('index.php/products/featureProducts').query().$promise.then(function(data){
            angular.foreach(data,function(item) {
                 specialProducts.push(item);
            });
        });
    }

But in your controller you need to know when the data was returned from remote call for which you can watch over the specialProducts array.

Update: Better would be to use promises, but in this case

$scope.specialProducts = specialProductFactory.getFeatureProducts();

would fill the array in future. To know when you need to watch

$scope.$watchCollection("specialProducts",function(data) { //Called when data updated});

I strongly suggest you work with promise based API and use the then methods to get handle async responses.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top