0

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!

3
  • you should do a directive Commented Apr 13, 2015 at 20:30
  • How is it redundant? What do your other usages look like? Commented Apr 13, 2015 at 20:30
  • @OliverSalzburg its all the same code as far as doing state reload on success. so in another controller it would be identical but OtherService.update instead of MyService.update Commented Apr 13, 2015 at 20:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
var commonFn = function(result) {
  if (result.Success) {
    $state.reload();
  }
  else {
    $state.go('^');
  }
}
MyService.update(val).then(commonFn);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.