JeroenE
JeroenE

Reputation: 703

Call function for each route in $routeProvider

I have got a little challenge and didn't find the solution yet. As I tried serveral things I'm asking your help so probably someone can lead me to the right direction.

I've got a routes.js in AngularJS. There am I using a $routeProvider. In each .when() I need to call a function (as I need to do something with the name).

$routeProvider
.when('/url', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url1', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url2', { templateUrl: '', /* callMyFunction('/url'); */ }) ....

This is just an example, I know this won't work. But to give you an idea what I'm trying to do. As you can see this will mess up my code (you need much more to get this working, so you'll get a lot of extra code for each .when() and this code is in every statement exactly the same (except for the argument).

So I'm looking for some function that can be called before or after (doesn't make sense as long as it's getting called) .when().

I've read plenty of questions here on Stack Overflow but didn't find the right answer. Most questions answered to put this in the controller. How ever, this function I've to call is for each route exactly the same. Because of this I don't want to put it in all my controllers but just in the routes.js and called for/after every when().

Upvotes: 3

Views: 2332

Answers (2)

Lex
Lex

Reputation: 7194

If you're willing to change to ui-router this all becomes much easier. ui-router is far superior to the built-in routing supplied with base Angular. Here is a simple example of how to execute a function with ui-router. In this example I set the value of a variable which is then injected in the controller as well as just call a simple function.

angular.module('app', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('main', {
      url: '/',
      template: '<div>This is the main state - mainValue: {{vm.mainValue}}</div>',
      controller: 'MainController',
      controllerAs: 'vm',
      resolve: {
        mainValue: function() {
          return 2 + 2;
        },
        function() {
          console.log('this is just calling a function with no return');
        }
      }
    });
  })
  .controller('MainController', function(mainValue) {
    this.mainValue = mainValue;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<div ng-app="app">
  <div ui-view></div>
</div>

Upvotes: 0

lealceldeiro
lealceldeiro

Reputation: 14958

You are looking for something like $routeChangeSuccess or $routeChangeStart (See $route).

Before route change

function runConfig($rootScope) {
    $rootScope.$on('$routeChangeStart', function (event, next, current) {
        if (next && next['$$route']) {
            var route = next['$$route']['originalPath'];
            //route is 'url', 'url1' or 'urlX'
            //do with it as you please
        }
    });
}

angular
        .module('app')
        .run(runConfig);

After route changed

function runConfig($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, prev) {
        if (current && current['$$route']) {
            var route = current['$$route']['originalPath'];
            //route is 'url', 'url1' or 'urlX'
            //do with it as you please
        }
    });
}

angular
        .module('app')
        .run(runConfig);

Upvotes: 2

Related Questions