鉴于下面的工厂,我需要在创建对象时传递id
,但是当我创建工厂时,我无法传递参数,因为我得到了无效的提供者。如何传递参数?
在控制器中:
var canvas = new FactoryCanvas(123);
工厂:
angular.module('app')
.factory('FactoryCanvas', function(id) {
var Canvas = function (id) {
this.id = id;
alert(id);
};
return Canvas;
});
答案 0 :(得分:1)
您的工厂定义错误,从Factory定义中删除id参数,由此导致提供程序错误。 Angular试图向你的工厂注入id,这实际上不是你想要的。
myApp.factory('FactoryCanvas', function() { // removed id
var Canvas = function (id) {
this.id = id;
alert(id);
};
return Canvas;
});
答案 1 :(得分:0)
为了更好地解释两者之间的区别(只是语法),添加更多功能是有帮助的
有工厂
var canvas = FactoryCanvas.Canvas(123);
angular.module('app')
.factory('FactoryCanvas', function() {
// This is private
var x = "x";
var foo = function foo(){
return "foo";
}
// This is public and can be accessed by the controller
return {
Canvas : function (id) {
alert(id);
},
getX : function(){
return x;
},
getFoo : foo
};
});
有服务
var canvas = FactoryCanvas.Canvas(123);
angular.module('app')
.service('FactoryCanvas', function() {
// Angular automatically creates a `new` object when called
// This is private!
var x = "foo";
var y = function(){
return "foo";
};
// This is public
this.Canvas = function (id) {
alert(id);
};
this.getX = function(){
return x;
};
});
从AngularJS启动并运行
在以下情况下使用工厂定义您的服务:
- 您遵循编程的功能风格 - 您更喜欢返回函数和对象。
很难相信这是唯一的区别,但确实如此 如您所见,服务更具可读性。
答案 2 :(得分:-1)
你需要像这样创建闭包
app.factory('Customerdetail',function($resource) {
return {
query: function(image_url) {
return $resource('customer/details', {}, {
query: { method: 'GET', params: {imageUrl:image_url}, isArray: false }
}).query();
}
}
});
现在在你的控制器中你可以写
function IndexCtrl($scope, Customerdetail) {
$scope.text = Customerdetail.query("YOUR/IMAGE/URL");
}