Reputation: 71
I am trying to call a function on a Service from a controller, in order to update the theme on my website, depending on which provider's section of the site i am on.
My Service,
MyApp.service('ThemeService', function() {
var ThemeProvider = 1;
var ThemeArea = "NotSet";
this.SetVariables = function() {
switch (ThemeProvider) {
case 1:
default:
ThemeArea = "Themes/Default";
break;
case 2:
ThemeArea = "Themes/Provider2";
break;
}
return ThemeProvider;
};
return {
ThemeProvider: ThemeProvider,
getThemeArea: ThemeArea,
};
});
My Controller
$scope.loadData = function (input) {
ThemeService.ThemeProvider = 2;
ThemeService.SetVariables();
};
My idea is that inside the controller, the function "SetVariables" can be called after the "ThemeProvider" is set, to change the "ThemeArea", but i cant work out how to call the function "SetVariables" from my controller.
When i try, i get an error
TypeError: Object doesn't support property or method 'SetVariables'
Upvotes: 0
Views: 60
Reputation: 2692
First of all your service returns an object which does not have any property called SetVariables
, that's why you get the error.Also this.SetVariables
will be looking for ThemeProvider
which is initialized in your service (var ThemeProvider = 1;
) and not the value assigned from controller.
Your code should be looking like this:
Service:
MyApp.service('ThemeService', function() {
var _ThemeProvider = 1;
var _ThemeArea = "NotSet";
angular.extend(this, {
SetVariables,
setThemeProvider,
setThemeArea,
getThemeProvider,
getThemeArea
})
function SetVariables() {
switch (_ThemeProvider) {
case 1:
default:
_ThemeArea = "Themes/Default";
break;
case 2:
_ThemeArea = "Themes/Provider2";
break;
}
return _ThemeProvider;
};
function setThemeProvider(val) {
_ThemeProvider = val;
};
function getThemeProvider() {
return _ThemeProvider;
};
function setThemeArea(val) {
_ThemeArea = val;
}
function getThemeArea() {
return _ThemeArea;
}
});
Controller:
$scope.loadData = function(input) {
ThemeService.setThemeProvider(2);
ThemeService.SetVariables();
};
Upvotes: 0
Reputation: 7188
You're not returning SetVariables
, see at the bottom of your Service definition there's a return statement, it should contain everything you want to be accessible.
return {
ThemeProvider: ThemeProvider,
getThemeArea: ThemeArea,
SetVariables: SetVariables
};
Upvotes: 1