Angularjs 如何从控制器访问工厂
我有一个Angularjs 如何从控制器访问工厂,angularjs,dependency-injection,Angularjs,Dependency Injection,我有一个工厂如下: rasm.factory('serviceUrl',[function(){ function serviceUrl(){ this.p = location.protocol; this.h = getHost(); } serviceUrl.prototype.getServiceUrl = function(){ return this.p +'//'
工厂
如下:
rasm.factory('serviceUrl',[function(){
function serviceUrl(){
this.p = location.protocol;
this.h = getHost();
}
serviceUrl.prototype.getServiceUrl = function(){
return this.p +'//'+ this.h + '/services/'
}
}])
rasm.factory('serviceUrl', [function() {
var _this = this;
_this.p = location.protocol;
_this.h = getHost();
return {
getServiceUrl: function() {
return _this.p +'//'+ _this.h + '/services/'
}
}
}]);
我已经用javascript面向对象的方式实现了它
我的问题是,如何从控制器访问此函数。这可能吗?谢谢大家阅读。您首先需要更改工厂代码:
rasm.factory('serviceUrl',[function(){
function serviceUrl(){
this.p = location.protocol;
this.h = getHost();
}
serviceUrl.prototype.getServiceUrl = function(){
return this.p +'//'+ this.h + '/services/'
}
// This line has been added
return serviceUrl;
}]);
然后在控制器中使用它:
myApp.controller('MyCtrl', ['$scope', 'serviceUrl', function($scope, serviceUrl) {
serviceUrl.getServiceUrl();
}]);
更新
我建议您这样更改工厂代码:
rasm.factory('serviceUrl',[function(){
function serviceUrl(){
this.p = location.protocol;
this.h = getHost();
}
serviceUrl.prototype.getServiceUrl = function(){
return this.p +'//'+ this.h + '/services/'
}
}])
rasm.factory('serviceUrl', [function() {
var _this = this;
_this.p = location.protocol;
_this.h = getHost();
return {
getServiceUrl: function() {
return _this.p +'//'+ _this.h + '/services/'
}
}
}]);
我想我必须从serviceUrl创建对象。如下所示:var obj=new serviceUrl();obj.getServiceUrl()否,Angular中的工厂在应用程序的整个生命周期中都是单例的,这意味着Angular只在内部执行相同的操作(
new serviceUrl
),然后使用DI使同一实例在任何地方都可用。实际上这不是真的,Angular不为工厂调用新的,但只在配方返回(和缓存)结果时执行配方。在这种情况下,我认为使用服务更合适。@Shashank Agrawal它给我这个错误serviceUrl.getServiceUrl不是一个函数