Find a route from angularjs rubeprovider by name

I define my routes as follows.

$routeProvider
.when('/Home', {
     name: 'Main',
     templateUrl: 'Main.html',
     controller: 'MainController',
     controllerAs: 'ctrl'
})
.when('/About', {
     name: 'About',
     templateUrl: 'About.html',
     controller: 'AboutController',
     controllerAs: 'ctrl'
})

How can I find the “/ About” URL in the controller by requesting the name “About” when I am in the main controller?

+4
source share
4 answers

Since nothing has been built, extending the route can solve this problem nicely:

$provide.decorator('$route', ($delegate) => {

    $delegate.getRoute = (name) => {
        var result = null;
        angular.forEach($delegate.routes, (config, route) => {
            if (config.name === name) {
                result = route;
            }
        });
        return result;
    };

    return $delegate;
});
+7
source

You can enter $locationinto your controller and get the URL using $location.path()or paste $routeto get the name of the route.

Example:

function MainCntl($scope,$location,$route) {
  $scope.location = $location.path(); // '/Home'
  $scope.routeName= $route.current.$$route.name; //'Main'
}
+7
source

:

:

Object.getPrototypeOf($route.current) === $route.routes['/Home'];

, , $routeChangeSuccess, :

$rootScope.$on('$routeChangeSuccess', function(e, curr, prev) {
    if (Object.getPrototypeOf($route.current) === $route.routes['/Home']) {
         // do something when route changes to /Home
    }

    else if (Object.getPrototypeOf($route.current) === $route.routes['/About']) {
         // do something when route changes to /About
    }
}

( , angular ). .

, ( $route.current $route.routes , ), .

IE9 +.

0

URL, :

function MainCntl($scope, $location) {

    // put this at where your want to find the '/About' URL
    $location.path('/About'); 

}
-1

Source: https://habr.com/ru/post/1524450/


All Articles