你的過濾器應該是這樣的,它應該在transformResponse在$資源查詢,而不是服務調用,我希望這將幫助你
'use strict';
angular.module('navbar').filter('category', function() {
return function(categories) {
var categoryIds = ['World'];
var result = [];
angular.forEach(categoryIds, function (categoryId) {
angular.forEach(categories, function (category) {
if (category.name == categoryId) {
console.log("Match");
result.push(category);
}
});
});
return result;
};
});
你categoryResource.service應該是這樣的
angular.module('shared').factory('categoryResourceService',
['$resource','categoryFilter', function($resource, categoryFilter) {
var provider = "categories.json";
var params = {
id: '@id'
};
return $resource(provider, params, {
query: {
isArray: true,
method: 'GET',
params: {},
transformResponse: function(categories) {
var results = categoryFilter(angular.fromJson(categories));
console.log("[categoryResourceService] filtered response:", results);
return results;
}
}
});
}]);
navbar.service應該是這樣的簡單
'use strict';
angular.module('navbar')
.service('navbarService', [ 'categoryResourceService', function (categoryResourceService) {
var vm = this;
vm.getCategories = function(){
vm.categories = categoryResourceService.query(function(response){
console.log("[NavbarService] response:", response);
}, function(error){
console.log("[NavbarService] error:", error);
});
return vm.categories;
}
}]);
個組件這樣
'use strict';
angular.module('navbar').component('appNavbar', {
templateUrl: "navbar.template.html",
controller: [ 'navbarService', function appNavbarController(navbarService) {
var vm = this;
vm.categories = navbarService.getCategories();
}]
});
你在getCatagories函數中聲明瞭一個局部變量,它在過濾器函數 –
@GhulamMohayudin中傳遞它時無法訪問你能否請你解釋一下?我沒有看到問題將category變量傳遞給categoryFilter,因爲它們處於相同的級別,此外,您可以將代碼直接複製粘貼到服務中的CategoryFilter中,但它仍然不起作用。 – Habchi
好的,讓我爲你添加一個答案 –