我有这样的factory
:
rasm.factory('serviceUrl',[function(){
function serviceUrl(){
this.p = location.protocol;
this.h = getHost();
}
serviceUrl.prototype.getServiceUrl = function(){
return this.p +'//'+ this.h + '/services/'
}
}])
我已经用JavaScript面向对象的方式实现了这个,这是我使用的资源。https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc#.du8tor7h2
我的问题是,如何从控制器访问此getServiceUrl函数。 这可能吗? 谢谢大家
阅读有关依赖注入的信息。您首先需要更改该工厂代码:
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() {
var _this = this;
_this.p = location.protocol;
_this.h = getHost();
return {
getServiceUrl: function() {
return _this.p +'//'+ _this.h + '/services/'
}
}
}]);