1

I got the following working great in each controller.

$scope.$on('$routeChangeStart', function(event){
    $scope.closeitup();
});

And in every controller i got a closeitup() function that does something different but with the same name.

How can i move the above $scope.$on to a service that will be fired and call the controller closeitup()

Hope the question is clear enough

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
user3052526
  • 681
  • 10
  • 24

2 Answers2

0
myModule.factory('closeitupOnRouteChangeStart', function() {
  return function($scope) {
    $scope.$on('$routeChangeStart', function() {
      $scope.closeitup();
    });
  };
}); 

and in the controller:

myModule.controller('SomeCtrl', function($scope, closeitupOnRouteChangeStart) {
  closeitupOnRouteChangeStart($scope);
});

I'm not sure this makes the code cleaner and more readable, though.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

What about using $controller inheritance?

app.controller('ParentCtrl ', function($scope) {
  $scope.$on('$routeChangeStart', function(event){
    $scope.closeitup();
  });
});

app.controller('ChildCtrl', function($scope, $controller) {
  $controller('ParentCtrl', {$scope: $scope});
});

Didn't tried that myself, so sorry if the approach is misleading.

Community
  • 1
  • 1
ElMesa
  • 928
  • 8
  • 19
  • I did not try this but i want to move the code to a service. thanks though i will look into `$controller` as i did not know about it – user3052526 Oct 31 '15 at 09:38
  • If you just need to encapsulate that logic somewhere, the controller inheritance sounds good. If not, try "JB Nizet" answer, and please give him accepted state if it solves your problem. :D – ElMesa Oct 31 '15 at 10:18