Currently, I am in the process of refactoring a complex and extensive form that primarily operates within a controller. To streamline the process, I have started segregating related functions into separate modules or services. However, I am grappling with the issue of managing form data effectively without cluttering the controller or having to pass an overwhelming number of arguments to service functions.
My existing approach involves setting variables on the service, then attempting to access this saved data in other services. Unfortunately, this method doesn't seem to be yielding the desired results as injecting the service into another creates a new instance void of any saved values.
To showcase this methodology, here is a plunker demonstrating my implementation: https://plnkr.co/edit/vyKtlXk8Swwf7xmoCJ4q
let app = angular.module('myApp', []);
app.service('productService', [function() {
let products = [
{ name: 'foo', value: 'foo' },
{ name: 'bar', value: 'bar' },
{ name: 'baz', value: 'baz' }
];
let selectedProduct = null;
this.getAvailableProducts = function() {
return products;
}
this.setSelectedProduct = function(product) {
selectedProduct = product;
}
}]);
app.service('storeService', ['productService', function(productService) {
let states = [
{ name: 'SC', value: 'SC' },
{ name: 'GA', value: 'GA' },
{ name: 'LA', value: 'LA' }
];
let selectedState = '';
this.getAvailableStates = function() {
return states;
}
this.setSelectedState = function(state) {
selectedState = state;
}
this.getPrice = function() {
// This console.log will always return undefined.
// productService.selectedProduct is not available.
console.log(productService.selectedProduct);
if (productService.selectedProduct == "foo" && selectedState == 'SC') {
return 10;
}
return 5;
}
}]);
app.controller('myController', function($scope, storeService, productService) {
$scope.name = '';
$scope.deliveryState = '';
$scope.selectedProduct = null;
$scope.price = 0;
$scope.productSelection = productService.getAvailableProducts();
$scope.states = storeService.getAvailableStates();
$scope.productChanged = function() {
productService.setSelectedProduct($scope.selectedProduct);
$scope.price = storeService.getPrice();
}
$scope.stateChanged = function() {
storeService.setSelectedState($scope.deliveryState);
$scope.price = storeService.getPrice();
}
});
I am trying to avoid something like this:
$scope.price = storeService.getPrice(
$scope.state,
$scope.selectedProduct,
$scope.servicePackage,
$scope.serviceFee,
$scope.shippingSelection,
// etc…
);
Perhaps I should consider creating a third service to manage and transfer all data between the other services?
Or maybe it would be better to maintain all the data solely within the controller?