I have 2 controllers (Products) and (ProductsFilters) and 1 service (ProductService).
2 controllers are loaded at the same time as the second (ProductFilter) acts as a side menu for the first controller (Products).
The product controller calls the AJAX service through the ProductService and assigns the returned data to the variable (Facets) in the ProductService.
At the same time, ProductFilter extracts (Facets) from the ProductService.
Now the problem is that I want to process some data in the ProductFilter controller before it is displayed in the view, but at runtime ProductService.Facets returns an empty object because the AJAX call is not finished yet
I tried $ watch () ProductService.Facets, but that didn't work.
Here is the product service
.factory('ProductService', function(AppService, CategoryService, $stateParams, $location, $http) {
return {
facets: {},
browse: function(category_id, page, order, order_type) {
url = AppService.apiUrl() + 'products/browse.json?' + params;
var that = this;
return this.getProducts(url).then(function(response) {
that.facets.grouped_brands = response.grouped_brands;
that.facets.grouped_categories = response.grouped_categories;
that.facets.grouped_prices = response.grouped_prices;
that.facets.grouped_stores = response.grouped_stores;
return response;
});
},
getProducts: function(url) {
return $http.jsonp(url + '&callback=JSON_CALLBACK&ref=mobile_app', {cache: true})
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
}
});
}
}
})
Here is the product controller:
.controller('ProductsController', function($scope, ProductService) {
$scope.page = 1;
$scope.moreProducts = function() {
ProductService.browse(180, $scope.page)
.then(function(products) {
angular.extend($scope.products, products.products);
$scope.page +=1;
}
);
}
$scope.products = {}
})
And here is the ProductFilter controller:
.controller('ProductsFiltersController', function($scope, ProductService) {
$scope.facets = ProductService.facets;
$scope.brand_facets = []
$scope.$watch('facets', function() {
angular.forEach($scope.facets.grouped_brands, function(value, key) {
$scope.brand_facets.push({brand: key, count: value})
});
});
})