Siddharth
Siddharth

Reputation: 102

Do we need multiple controllers to implement routes in angularjs?

There is chance that I might not be able to explain my problem properly. Let me try.

I am developing a single page application using angular. This app basically displays the episodes of an online novel series. There is a navigation bar, which has query menus (Like, latest episode, episode of a particular date, episodes with a particular tag, etc). For each of these queries, i want a separate url.

/latest - should display the latest episode

/tag/:tagname - should return all episodes with that tag.

For all these queries, the resultant view is the same (list of episodes). So I will be using the same partial for all routes.

My question is, Should I actually create a new controller for each query? like, LatestEpisodeController, TagController?

Is there anyway I can use the url to determine what the user wants and run that query from within the same controller?

Upvotes: 1

Views: 133

Answers (3)

Anita
Anita

Reputation: 2400

yes you can use single controller for multiple routing.. you can create different functions in controller and in each function do the according job. In my case I have created different html page for different url and registered same controller for the html pages and in the html page I have called controller method using ng-init in div portion.

Upvotes: 2

Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

You can use same controller and same views as you wish... $location can help you to get current path or full url if you want and you can call your service depends on your path...

here I write a little example for you to get the idea

PLUNKER

Upvotes: 1

maurycy
maurycy

Reputation: 8465

Ofcourse you can use same controller in routing definition, the question is what is the purpose of that? It will be worse to debug it later, if you have a shared functionality it's better to turn it into a factory or service and then use in controllers.

But the answer is YES, you can use same controllers and implement different behaviour basing on i.e. $location.path()

Upvotes: 2

Related Questions