How to route without a templateUrl?

萝らか妹 提交于 2019-12-02 20:08:29
Lukas

A workaround is to use template instead of templateUrl. From the Angular docs:

template – {string=} – html template as a string that should be used by ngView or ngInclude directives. this property takes precedence over templateUrl.

This can be used as follows:

$routeProvider.when("/foo", {template: " ", controller: "Ctrl"});

Note: You must use " " instead of an empty string "" because Angular uses an if (template) check before firing the controller, and an empty string evaluates to false.

-- EDIT --

A better way to do it is to use the resolve map. See the Angular Docs:

resolve - {Object.=} - An optional map of dependencies which should be injected into the controller.

This can be used like this:

$routeProvider.when('/foo', {resolve: {redirect: 'RedirectService'}});

Note: I've changed it from "Ctrl" to "RedirectService", because what you're describing in the question isn't really a "controller" in the Angular sense. It doesn't set up scope for a view. Instead, it's more like a service, which ends up redirecting.

I am writing the solution based on the already accepted answer and the github issue mentioned in it's comments.


The approach I am using is a resolve parameter in the $routeProvider. In my case I was trying to create a nice solution to logout in my application, when user goes to /logout.

Example code of $routeProvider:

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        ...
        when('/logout', {
            resolve: {
                logout: ['logoutService', function (logoutService) {
                    logoutService();
                }]
            },
        }).
        ...
}]);

In the resolve part you specify a service (factory) by name and later on you have to call it. Still it is the nicest solution around.

To make the example complete I present my logoutService:

angular.module('xxx').factory('logoutService', function ($location, Auth) {
    return function () {
       Auth.setUser(undefined);
       $location.path('/');
    }
});

Works great!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!