UI-Router Multiple Views Single Controller

Is it possible to have multiple views [ https://github.com/angular-ui/ui-router/issues/494] using a singleton controller?

Use case: I have ui-view = header and ui-view = content. I change the title depending on the current state to display contextual relative buttons (e.g. go back, save, filter, etc.). I want these buttons to call a function in the content controller, but if I do the following, they will create two MyController objects. If there are any init functions, they are called twice, which in most cases doubles the requests to my server.

views:{ 'header':{ templateURL:'...', controller:'MyController' }, 'content':{ templateURL:'...', controller:'MyController' } } 

Update: Based on @pankajparkar

My current index.html looks like this (simplified to understand)

 <nav ui-view="header"></nav> <div ui-view="content"></div> 

But your proposal will consist of / REQUIRE subviews

 <!--index.html--> <body ui-view></body> <!--format.html--> <nav ui-view="header"></nav> <div ui-view="content"></div> 

With the following controller

 state('app', { url: '/app', controller: 'MyController', templateURL: 'format.html', //Targets ui-view in index.html views:{ 'header':{ templateURL:'...', //Targets ui-view="header" in format.html }, 'content':{ templateURL:'...', //Targets ui-view="header" in content.html } } }); 
+8
angularjs angular-ui-router
source share
3 answers

You basically need to process such things from some provider (usually services or factory), which are singleton, and then you can enter a singleton into the controller, and each instance of the controller will use the same / common provider.

If you need help implementing this, please share your controller.

Although I agree with the suggestions in another answer posted here, you might want to consider including functionality in the provider. In most situations, it is best for you to use most of the functions and data that live in providers, and that your controllers are responsible for going through user interactions to cause the corresponding call to the providers (and it will fix your current problem, since they are singleton).

+2
source share

You must place this controller outside of views so that it loads only once per page

 $stateProvider.state("abc",{ url:'/abc', templateUrl: 'abc.html', controller:'MyController', //<---place it here will load it once views:{ 'header':{ templateURL:'...' }, 'content':{ templateURL:'...' } } }) 
+1
source share

I work this way:

 $stateProvider.state("abc",{ url:'/abc', views:{ '':{ templateUrl: 'abc.html', controller:'MyController' <-- it also attached to subviews }, 'header@abc':{ templateURL:'...' }, 'content@abc':{ templateURL:'...' } } }) 
+1
source share

All Articles