i have a function
function propValueFilter (toFilterArr, filterFunction) {
return toFilterArr.filter(filterFunction);
};
and a factory
backpackrApp.factory('itemsFactory', function(propValueFilter) {
factory.getBackpackById = function(id) {
return backpacks.propValueFilter(function(element) {
return element.id == id;
});
};
return factory;
});
I am getting a Unknown Provider error in component $injector in the Webconsole.
How to inject a function right? I want to create a set of Helper functions which i can use in many controllers / factorys etc.
Thanks in Advance
You should wrap this function in another service/factory (named filterService in example below) and inject that into the items factory, like:
backpackrApp.factory('itemsFactory', ['filterService', function(filterService) {
factory.getBackpackById = function(id) {
return backpacks.propValueFilter(function(element) {
return element.id == id;
});
};
return factory;
}]);
Spacing issue in the return of the 1st function? Should be:
function propValueFilter (toFilterArr, filterFunction) {
return toFilterArr.filter(filterFunction);
};
I think you want to create helper functions you can inject them from a factory (assuming you know what you're doing with Array.filter):
backpackrApp.factory('myUtil', function() {
var obj = {
obj.propValueFilter = function(toFilterArr, filterFunction) {
return toFilterArr.filter(filterFunction);
};
};
return obj;
});
backpackrApp.factory('itemsFactory', function(myUtil) {
var itemsFactoryObj = {
backpacks = []; // set somewhere
obj.getBackpackById = function(backpacks, id) {
return myUtil.propValueFilter(function(element) {
return element.id == id;
});
};
};
return itemsFactoryObj;
});
backpackrApp.controller('TestCtrl', function(itemsFactory) {
$scope.backpack = itemsFactory.getBackpackById(1);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.