UI路由器多视图单个控制器 [英] UI-Router Multiple Views Single Controller

查看:55
本文介绍了UI路由器多视图单个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能有多个视图[ https://github.com/angular-ui/ui-router/issues/494] 和单例控制器?

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

用例:我有一个ui-view = header和ui-view = content.我根据当前状态更改标题以显示上下文相关的按钮(即返回,保存,过滤等).我希望这些按钮在内容控制器中调用一个函数,但是如果执行以下操作,它将创建两个MyController对象.如果有任何初始化函数,它们将被调用两次,这在大多数情况下是对我的服务器的查询的两倍.

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'
  }
}

更新:基于@pankajparkar

Update: Based on @pankajparkar

我当前的index.html看起来像这样(为便于理解而简化)

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>

使用以下控制器

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
    }
  }
});

推荐答案

您基本上需要在单身人士的某种提供程序(通常是服务或工厂)中处理此类问题,然后可以将单身人士注入控制器和控制器的每个实例都将使用共享/相同的提供程序.

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

这篇关于UI路由器多视图单个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆