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

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

问题描述

是否可以有多个视图 [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>

但您的建议将包含/REQUIRE 子视图

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-Router 多视图 单控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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