Break large services into smaller services with the same interface. Angular-delegator will wire them up for you based on your configuration.
Please note: Angular Delegator is a very young project. The API is likely to change in the near future.
If you had a large validation service that checked an account's name, date, address and payment info, you could break it down like so:
angular.module('myApp', ['delegator'])
.factory('AccountValidator', function(Delegator) {
return Delegator.create({
interface: {
'isValid': 'all'
},
delegates: [
'AccountNameValidator',
'AccountDateValidator',
'AccountAddressValidator',
'AccountPaymentValidator'
]
});
});
The interface
option defines which methods should be handled by the delegator, and which delegator strategy to use. If none of the built-in strategies are sufficient, you can easily write your own, easily testable custom delegator strategies.
In this example, your application now has an AccountValidator
service with a single method called isValid
:
angular.module('myApp').controller('SomeCtrl', function($scope, AccountValidator) {
AccountValidator.isValid($scope.data);
});
Rather than manually creating a delegator service, it can be generated for you dynamically in your module's config step:
angular.module('myApp', ['delegator'])
.config(function(DelegatorProvider) {
DelegatorProvider.service('AccountValidationDelegator', {
interface: {
'isValid': 'all'
},
delegates: [
'AccountNameValidationDelegate',
'AccountDateValidationDelegate',
'AccountAddressValidationDelegate',
'AccountPaymentValidationDelegate'
]
});
});
<tr>
<th>map</th>
<td>Returns an array of everything returned from the delegates</td>
<tr>
<th>merge</th>
<td>Returns a single object, the result of merging all objects returned from the delegates</td>
<tr>
<th>truthy</th>
<td>Returns an array of all truthy values returned from the delegates</td>
<tr>
<th>any</th>
<td>Returns true if any delegate returns true</td>
<tr>
<th>all</th>
<td>Returns true if all delegates return true</td>
<tr>
<th>none</th>
<td>Returns true if no delegates return true</td>
Strategies are implemented as services ending with 'DelegatorStrategy'. All built-in delegator strategies are defined this way, and can be injected into your custom strategies.
For example,
angular.module('myApp')
.factory('FoobarDelegatorStrategy', function(AllDelegatorStrategy) {
return function(fns, args) {
// Here you have access to the delegate functions
// and the arguments passed to the delegator.
return AllDelegatorStrategy(fns, args);
};
})
.config(function(DelegatorProvider) {
DelegatorProvider.service('AccountValidationDelegator', {
interface: {
'isValid': 'foobar'
},
delegates: [
'AccountNameValidationDelegate',
'AccountDateValidationDelegate',
'AccountAddressValidationDelegate',
'AccountPaymentValidationDelegate'
]
});
});
$ bower install --save angular-delegator
Download the production version or the development version.