Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI-Router Multiple Views Single Controller

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

Use case: I have a ui-view=header and ui-view=content. I change the header depending on the current state to display context relative buttons (ie go back, save, filter, etc.) I want those buttons to call a function in the content controller, but if I do the following it creates two MyController objects. If there's any init functions they get called twice, which in most cases is double the queries to my server.

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

Update: Based on @pankajparkar

My current index.html looks like this (simplified for understanding)

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

But your suggestion would 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
    }
  }
});
like image 321
Ryan H Avatar asked Apr 17 '15 19:04

Ryan H


2 Answers

You basically need to handle this kind of stuff in some sort of provider (typically a service or a factory) those are singletons and then you can inject the singleton into the controller and each instance of the controller will be using the shared/same provider.

If you need help implementing this please share your controller.

Although I do agree with the suggestions in the other answer posted here, you may want to consider putting the functionality in a provider anyhow. In most situations you're best off having most of the functionality and data living in providers and having your controllers just be responsible for passing along the user interactions to trigger the appropriate call in the providers (and it would fix your current problem since they are singletons).

like image 149
shaunhusain Avatar answered Nov 02 '22 23:11

shaunhusain


I have it working in this way:

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

})
like image 22
Musma Avatar answered Nov 03 '22 01:11

Musma