如何从$ routeProvider中删除路由

时间:2014-07-09 14:16:22

标签: angularjs

是否可以从$ routeProvider中删除路由?

app.config(function($routeProvider) {$routeProvider
.when('/test', {
    templateUrl:'/index.html',
controller: 'mainCtrl'
})});

如何删除' / test'来自提供商的路由以及templatecache?

1 个答案:

答案 0 :(得分:4)

因此,为了删除您需要的路线:

  1. 可以访问$route.routes
  2. 知道要删除的路径。
  3. 可以访问$templateCahce
  4. 找出与路径相关联的templateUrl
  5. (请记住,$routeProvider始终会注册两条路线:一条路线有/而另一路没有 - 只是为了涵盖两种情况。)

    function headerCtrl($location, $route, $scope, $templateCache) {
        ...
        // For simplicity's sake we assume that:
        //  1. `path` has no trailing `/`
        //  2. the route associated with `path` has a `templateUrl`
        //  3. everything exists, so we don't check for empty values
        $scope.removeRoute = function (path) {
            var route1  = $route.routes[path];
            var route2  = $route.routes[path + '/'];
            var tmplUrl = $route.routes[path].templateUrl;
    
            $templateCache.remove(tmplUrl);
            delete(route1);
            delete(route2);
    
            // It might also be a good idea 
            // to move to another, default path
            $location.path('/');
        };
    

    另请参阅此 short demo