Reputation: 41455
I have a factory
like this:
rasm.factory('serviceUrl',[function(){
function serviceUrl(){
this.p = location.protocol;
this.h = getHost();
}
serviceUrl.prototype.getServiceUrl = function(){
return this.p +'//'+ this.h + '/services/'
}
}])
i have implemented this in javascript object oriented way.this is the resource that i have used https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc#.du8tor7h2
My problem is, how can I access this getServiceUrl function from my controller. is this even possible? thanks guys
Upvotes: 2
Views: 1062
Reputation: 25817
Read about Dependency Injection. You first need to change that factory code:
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;
}]);
Then use it in your controller:
myApp.controller('MyCtrl', ['$scope', 'serviceUrl', function($scope, serviceUrl) {
serviceUrl.getServiceUrl();
}]);
Update
I suggest you changing your factory code like this:
rasm.factory('serviceUrl', [function() {
var _this = this;
_this.p = location.protocol;
_this.h = getHost();
return {
getServiceUrl: function() {
return _this.p +'//'+ _this.h + '/services/'
}
}
}]);
Upvotes: 4