我找到了一个非常有用的教程,可以创建一个带参数的角度工厂。无论多么有用,都会出现打嗝。
下面,工厂创建一个function-object / constructor的实例。本教程的作者没有解释这个"库存"应该放置构造函数。
"库存"构造函数进入一个单独的文件,比如模块/ IFFE?
/* WHERE DOES THIS INVENTORY OBJECT GO?? */
function Inventory($http, url, project_id) {
/** The public method for getting the project price **/
this.price = function(callback) {
$http.get(url+"?project="+project_id)
.success(function(value) {
callback(value);
});
};
};
angular.factory('InventoryFactory',[
'$http',
/** This is the factory method that Angular will execute only ONCE **/
function InventoryFactory($http) {
/** This is the function that will be injected into the directive, and called multiple times by the programmer **/
return function(url, product_id) {
/** this is the new object that will be created and used by the programmer **/
return new Inventory($http, url, product_id);
};
}]);
angular.directive('inventoryStatus',['InventoryFactory',function(InventoryFactory) {
return {
link: function($scope,$el,$attr) {
var inventory = InventoryFactory('/api/projects',$scope.project_id);
inventory.price(function(value){
$scope.price = value;
});
}
}
}]);
提前致谢!