Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to route without a templateUrl?

Ok. I have a url setup to log a user out. On the server, there is no html. The session on the server simply gets destroyed, and then the user is redirected to an address.

This works fine with plain html, but with Angular i am having issues. I've been routing all main routes using $routeProvider.when('/foo', {templateUrl: '/foo.html', controller: 'Ctrl'}) and that works fine for normal templated routes.. however, if there is no template it will not work.

So, how do i support the route /logout in the same fashion as above, when there is no html template?

like image 923
Lee Olayvar Avatar asked Jan 19 '13 06:01

Lee Olayvar


People also ask

What is ng route?

AngularJS ngRoute module provides routing, deep linking services and directives for angular applications. We have to download angular-route. js script that contains the ngRoute module from AngularJS official website to use the routing feature. You can also use the CDN in your application to include this file.

Which directive can you use if you want to display views for a given router?

The directive ( <ng-outlet> ) that marks where the router should display a view. The directive ( ng-link="..." ) for binding a clickable HTML element to a route, via a Link Parameters Array.

What is use of$ routeProvider in AngularJS?

We use $routeProvider to configure the routes. The config() takes a function which takes the $routeProvider as parameter and the routing configuration goes inside the function. $routeProvider is a simple API which accepts either when() or otherwise() method.


1 Answers

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.

like image 130
Lukas Avatar answered Sep 24 '22 17:09

Lukas