最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I get the angularJS routeProvider to perform an action before the route change? - Stack Overflow

programmeradmin7浏览0评论

Let's say I have this config:

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider
        .when('/', { 
            templateUrl: 'app/partials/index.html',
            controller: 'defaultCtrl'
        })
        .when('/other', {
            templateUrl: 'app/partials/other.html',
            controller: 'errorCtrl'
        })
        .otherwise({ 
            templateUrl: 'app/partials/404.html'
        });
  }
]);

I'm looking for a place to do some basic, mon maintenance code before the router calls the route. Say I'd like to clear the console log via console.clear() every time the route is changed. How and where would be the best place in the code to do that?

Let's say I have this config:

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider
        .when('/', { 
            templateUrl: 'app/partials/index.html',
            controller: 'defaultCtrl'
        })
        .when('/other', {
            templateUrl: 'app/partials/other.html',
            controller: 'errorCtrl'
        })
        .otherwise({ 
            templateUrl: 'app/partials/404.html'
        });
  }
]);

I'm looking for a place to do some basic, mon maintenance code before the router calls the route. Say I'd like to clear the console log via console.clear() every time the route is changed. How and where would be the best place in the code to do that?

Share Improve this question edited Apr 14, 2015 at 9:42 vidriduch 4,8638 gold badges44 silver badges65 bronze badges asked Nov 5, 2013 at 10:56 Nir GavishNir Gavish 1,0443 gold badges13 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

The $route service raise events like $routeChangeStart which you can use to perform such tasks. You can implement them using the $scope.$on method. Someting like

$scope.$on('$routeChangeStart',function(angularEvent,next,current) {
  //do you work here
});

Read the $route documentation to get idea on this and other such events.

Also $routeProvider configuration method when also can take a parameter resolve which actually is used to setup dependencies before the route is resolved. This resolve object map can also be used to achieve what you want to do.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论