0

I have an Angular application with different types of pages, all identified by a slug right after the base url, so like:

http://example.com/slug-a
http://example.com/slug-b

Slug a and b are of different types and need to be rendered in a different view. The data belonging to the objects identified by slug a and b is fetched from the server, and the Angular application is supposed to change the view based on the object type.

Is it possible to handle this in the ngRoute's $routeProvider? I can't find any documentation that helps me with this, and I'm sure I'm not the first one to try this..

So, in short:

  • Client requests slug A => Angular requests data from Server => Angular loads ControllerA with template A.
  • Client requests slug B => Angular requests data from Server => Angular loads ControllerB with template B

Different view based on server response.

Keugels
  • 790
  • 5
  • 15
  • It is basic route definition. do you have route configured in your app? https://docs.angularjs.org/api/ngRoute/provider/$routeProvider. – Muthukannan Kanniappan Jun 14 '16 at 11:16
  • Yes, I have multiple routes. The last route /:slug catches all other routes. Angular requests data from the server (identified by the slug parameter) and based on the data that is returned I need to display a certain template. (The slug could be a user name, country or city for example. Users, countries and cities are displayed using different templates) – Keugels Jun 14 '16 at 11:28

2 Answers2

0

I think you can not do that in router. But you can redirect user to a different location via the $location service. Like this

// somewhere inside your controller 
var promise = loadData().then(data => {
    if (data.slugA) {
        $location('path_to_slugA');
    }
    else if (data.slugB) {
        $location('path_to_slugB');
    }
    else {
    // do something else
    }
});
David Votrubec
  • 3,968
  • 3
  • 33
  • 44
  • That wouldn't work. The $location.path() can't change anymore, as the user is already at the right URL. It only needs to load a different template based on the data returned by the server. The $location.path() can't change. – Keugels Jun 14 '16 at 11:25
  • I see ... in that case have a look at these two answers http://stackoverflow.com/questions/24496201/load-html-template-from-file-into-a-variable-in-angularjs and http://stackoverflow.com/questions/14788417/angular-load-template-from-url-and-compile-inside-div – David Votrubec Jun 14 '16 at 11:29
0

Ok, I've solved it using a different and much simpler approach. (Don't know why I didn't figure this out before)

$routeProvider.when('/:slug/', {
    controller: 'SlugController',
    template: '<div ng-include="template"></div>'
});

Then the SlugController makes the request and loads the right template by setting $scope.template. In the template file the controller attached to the root element.

Simple but effective.. :)

Keugels
  • 790
  • 5
  • 15