Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top