Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

angularjs - 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
    }
  }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...