我有一个角度滤镜设置很好用:
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.categories = store.getCategories();
$scope.products = store.getProducts();
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function(){
var categories = ['Lattes','CC Blend','Frappes'];
var products = [
{name: 'Latte machiatto',category: 'Lattes'},
{name: 'Frappe ice',category: 'Frappes'},
{name: 'Latte caramel',category: 'Lattes'},
{name: 'Frappe speculoos',category: 'Frappes'},
{name: 'Cappucino',category: 'CC Blend'},
{name: 'Filter coffee',category: 'CC Blend'},
];
return {
getCategories : function(){
return categories;
},
getProducts : function(){
return products;
}
};
});
但是var类别和var产品仍然是硬编码的,所以我想从我的服务器中检索所需的数据来填充这些变量。而我似乎无法做到这一点?我有另一个功能,我可以获得所需的数据,但我不知道如何获得这些2合1 ......?
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
});
});
那么如何正确地将var类别设置为所需的$ http.get以将我的服务器数据检索到上面的过滤器中呢?
答案 0 :(得分:2)
我认为您应该能够摆脱服务中的硬编码块并返回:
return {
getCategories: $http.get('/categories').success(function (data) {
return data;
}),
getProducts: $http.get('/products').success(function (data) {
return data;
})
}
确保为服务正确设置了依赖关系(即$http
):
.factory('store', function ($http) {
// The above return block here
});
这应该可以解决问题!