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.

2
  • It is basic route definition. do you have route configured in your app? docs.angularjs.org/api/ngRoute/provider/$routeProvider. Commented Jun 14, 2016 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) Commented Jun 14, 2016 at 11:28

2 Answers 2

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
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I see ... in that case have a look at these two answers stackoverflow.com/questions/24496201/… and stackoverflow.com/questions/14788417/…
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.. :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.