Reputation: 637
In all of my controllers I notice I have the same code over and over again after posting data. See below. Is there someway I can just pass my service to some sort of common function and handle everything there.
//user submits via click
$scope.submit = function(val) {
MyService.update(val).then(function(result) {
if (result.Success) {
$state.reload();
}
else {
$state.go('^');
}
})
}
Maybe turn this into just
$scope.submit = commonFn(MyService.update(val));
Any advice on the best way to avoid this redundant code would be great!
Upvotes: 0
Views: 79
Reputation: 20129
You could put the code into the Service and just pass the $state
in:
MyService
updateAndReload = function(val, $state){
update(val).then(function(result) {
if (result.Success) {
$state.reload();
}
else {
$state.go('^');
}
}
Controller
$scope.submit = MyService.updateAndReload(val, $state)
But this only works if it really is the exact same code every time. If there are more differences you probably just need to add more parameters.
Upvotes: 1
Reputation: 3747
var commonFn = function(result) {
if (result.Success) {
$state.reload();
}
else {
$state.go('^');
}
}
MyService.update(val).then(commonFn);
Upvotes: 0