I hava a ProdCache service used to cache a products array.
...
var products = ProdCache.get('all');
if(typeof products == 'undefined'){
products = Product.query();
ProdCache.put('all',products);
}
If I put products on the scope the products are shown as expected, but I need only a few products to be shown.
My try:
$scope.related = (function(){
var res = [];
if(products.length>0){
for (var i = 0, key; i < 3; i++) {
key = Math.floor(Math.random() * products.length);
res.push(products[key]);
}
}
return res;
})();
That function wont work the first time because the xhr request is being processed and the returned data is not reactive.
The proper way is to use filters docs here and here.
Assuming the filter you wrote is a mock, and you need a complex filter, you just have to create a filter function at $scope and reference it at ng-repeat expression:
$scope.isRelated = function isRelatedFilter(item) {
// if return is true, the item is included.
return item.someProperty === 'someCriteria';
}
<span ng-repeat="product in products | filter:isRelated">...</span>
The someCriteria could be another $scope/controller property or defined by a service. If you need custom parameters, than you can't use the filter filter and should create your own. Take a look at the docs.
Without the HTML code you are using for binding, it's a little difficult to determine how you are using your $scope.related function. However, if the only problem you are having is that, when the data comes back from the xhr request, the UI does not update, it is likely that your $digest phase has already ended and therefore the binding to $scope.related is not causing the function to re-fire until the next $digest phase.
This would probably work to handle the issue you are having:
...
var products = ProdCache.get('all');
if(typeof products == 'undefined'){
products = Product.query();
ProdCache.put('all',products);
// Add this line to force re-digest if needed
if(!$scope.$$phase) $scope.$digest();
}
Without seeing the HTML though, I'm not sure that this will solve your issue. If not, post a plunker so we can see the problem better.