AngularJS - 共享控制器之间的状态呢? [英] AngularJS - Shared state between controllers?

查看:79
本文介绍了AngularJS - 共享控制器之间的状态呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有关于如何角控制器之间的数据传递等类似的问题。

I know there are other similar questions on how to pass data between Angular controllers.

我想知道的是如何在一个视图处理这个..

What I wonder is how to deal with this in a view..

可以说我有一个UserController中进行登录,注册等。
和AppController的实际应用functionallity。

Lets say I have a UserController for login, registration etc. And an AppController for the actual app functionallity .

由于UserController将是相当容易的,它的排序从其他独立的。
但是,如果应用程序需要了解从用户控制器东西?

The UserController would be fairly easy, its sort of standalone from the rest. But what if the app needs to know about stuff from the user controller?

可以说应用程序视图需要取决于如果用户或没有登录显示/隐藏的东西。
或者它可以是如果用户是男性或女性等

Lets say the app view needs to hide/show stuff depending on if the user is logged in or not. Or it could be if the user is male or female etc.

如果该应用模型保持它自己的用户模型状态的副本?
例如appModel.isLoggedIn,appModel.gender等?

Should the app model keep its own copy of the user model state? e.g. appModel.isLoggedIn , appModel.gender etc ?

感觉有点多余,但同时更多的测试。

feels a bit redundant, but at the same time more testable.

那么,什么是做到这一点的正确方法?

So what is the correct way to do this?

推荐答案

创建服务,请参见创建服务了解详情。

Short answer

Create a service, see Creating Services for details.

服务是 - 本身 - 应用程序范围内单身,所以他们是完美的跨意见,控制器和放大器保持状态;合作:

Services are - per se - application-wide singletons, hence they are perfect for keeping state across views, controllers & co.:

app.factory('myService', [ function () {
  'use strict';
  return {
    // Your service implementation goes here ...
  };
}]);

一旦编写并注册服务,您可以使用AngularJS依赖注入功能,要求它在你的控制器:

Once you have written and registered your service, you can require it in your controllers using AngularJS' dependency injection feature:

app.controller('myController', [ 'myService', '$scope',
  function (myService, $scope) {
  'use strict';
  // Your controller implementation goes here ...
}]);

现在,你的控制器里面你有一个包含了服务的单一实例的为myService 变量。在那里,你可以有一个属性 isLoggedIn 的再presents用户是否登录或没有。

Now, inside your controller you have the myService variable which contains the single instance of the service. There you can have a property isLoggedIn that represents whether your user is logged in or not.

这篇关于AngularJS - 共享控制器之间的状态呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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