Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define the onEnter and onExit callbacks in another file with Angular UI Router

I have a simple application using Angular UI Router with some states.

Actually I have this kind of code in my router :

$stateProvider.state('map.layers', {
    url: '/layers',
    templateUrl: 'views/layers.html',
    controller: 'LayersCtrl',
    onEnter: function(map: Master.Map) {
      // do stuff
    },

    onExit: function(map: Master.Map) {
      // do stuff
    }
  });

The controller is defined in another file, and I'm looking for a good way to define the onEnter and onExit callbacks in the same file.

In your opinion, what is the best solution ? A global variable should work but it's not very beautiful.

like image 648
e741af0d41bc74bf854041f1fbdbf Avatar asked Nov 18 '13 16:11

e741af0d41bc74bf854041f1fbdbf


1 Answers

You can do this, but it without knowing more this is a code smell. You are mixing logic between controllers and states, but they should be separate.

Anyway, here's how you can do this:

In your controller, inject the $state object and use the $state.get method:

.controller('layersCtrl', function($state) {
  $state.get('map.layers').onEnter = blah;
  $state.get('map.layers').onExit = blahblah;
});

But rather than this, I would recommend that you extract this shared functionality into a service. If you are finding it hard to do this, then I would take a deep look at your code because there would seem to be too much coupling between modules.

like image 139
Andrew Eisenberg Avatar answered Nov 15 '22 05:11

Andrew Eisenberg