I have a controller that works fine, but it seems like it should be refactored to include a service.
My controller uses two functions to change a display of ingredients. One tied to a select element for mobile, the other tied to links for desktops.
Is it possible to refactor this to use a service?
My html for Mobile:
<select ng-model="ingredient.item" ng-options="i.option for i in ingredient.items" ng-change="ingredient.change_select(ingredient.item)">
<option value="">choose ingredient</option>
</select>
My html for Desktop:
<a ng-click="ingredient.change_tab('octopamine','Octopamine')">Octopamine</a>
My controller:
app.controller('IngredientsCtrl', function() {
var ingredient = this;
ingredient.items = [
{
'option': 'Brigham\'s Tea Leaf',
'param' : 'brighamtea'
},
{
'option': 'White Willow Bark Powder',
'param' : 'white_willow'
}];
ingredient.tab = 'brighamtea';
ingredient.tab_image = 'http://imgix.ximo365.com/brighamtea.jpg';
ingredient.tab_title = 'Brigham\'s Tea Leaf';
ingredient.change_select = function (item) {
ingredient.tab = item.param;
ingredient.tab_image = 'http://imgix.ximo365.com/' + item.param + '.jpg';
ingredient.tab_title = item.option;
}
ingredient.change_tab = function(param,title) {
ingredient.tab = param;
ingredient.tab_image = 'http://imgix.ximo365.com/' + param + '.jpg';
ingredient.tab_title = title;
}
});
1 Answer 1
Absolutely.
Create a factory/service like: IngredientsService
Use dependency injection to introduce this service in the controller.
// Example
app.controller('IngredientsCtrl'), function(IngredientsService) {
// Create reusable service methods
IngredientsService.change_select(item);
IngredientsService.change_tab(param, title);
});
You could also manage the default items list in the service to keep things DRY if you use this in multiple areas like other controllers, directives, or services.
Using services also lets you test in isolation and mock out dependencies in your controller.