我怎么可以访问另一个控制器的范围在一个控制器中定义的变量? [英] how can I access a variable defined in one controller from the scope of another controller?

查看:188
本文介绍了我怎么可以访问另一个控制器的范围在一个控制器中定义的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制器:
HeaderCtrl NewsFeedCtrl MainCtrl

I have the following controllers: HeaderCtrl, NewsFeedCtrl, MainCtrl

MainCtrl 包含其他两个控制器,这是在同一水平。

MainCtrl contains both the other two controllers, which are in the same level.

我在的AuthenticationService 定义对象,并在 MainCtrl 更新它的价值,我经常在更新 NewsFeedCtrl ,我想通过 HeaderCtrl 以显示其价值。

I'm defining an object in authenticationService and update its value in MainCtrl and I update it frequently in NewsFeedCtrl and I want to display its value in the HTML page controlled by HeaderCtrl.

当我使用这一行我的 HeaderCtrl

$scope.unreadNum=authenticationService.notificationList.length;

然后我用数据在我的HTML页面结合来显示它的值:

and then I use data binding in my HTML page to display its value:

{{unreadNum}}

我只得到我在的AuthenticationService 插入的初始值,而不是在其它控制器更新后的人。
看来我的 HeaderCtrl 是定义他的所有范围的对象只有一个时间,再有就是为Ctrl键不再使用,但我还是想在更新后更新自己的HTML页面在其他控制器对象值。

I only get the initial value I inserted in authenticationService, not the one after the update in the other controllers. it seems that my HeaderCtrl is defining all his scope objects only one time and then there's no more use for the Ctrl, but I still want his HTML page to be updated after the update in object values in other controllers.

来概括:我想保存在我的服务中的一个对象的价值,我无法在我的HTML页面中显示,因为我似乎把它绑定不能正确

to sum it up: the value of the object I want is stored in one of my services, and I am unable to display it in my HTML page because I can't seem bind it correctly.

推荐答案

您可以将使用服务控制器之间的消息。这项服务看起来是这样的...

You can send messages between the controllers using a service. The service looks something like this...

aModule.factory('messageService', function ($rootScope) {

var sharedService = {};

sharedService.message = {};

sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
};

sharedService.broadcastItem = function () {
    $rootScope.$broadcast('handleBroadcast');
};

return sharedService;
});

在正在发送消息的控制器,注入这项服务...

In the controller that is sending the message, inject this service...

aModule.controller("sendingController", function ($scope, messageService) {

然后添加将播出更改为监听任何控制器的方法...

Then add a method that will broadcast the change to any controller that is listening...

   $scope.sendMessage = function (someObject) {
        messageService.prepForBroadcast(someObject);
    },

在想要接收消息,注入的服务,并添加一个处理这样做的东西的信息任何控制器...

In any controller that wants to receive the message, inject the service, and add a handler like this to do something with the message...

  $scope.$on('handleBroadcast', function() {
       //update what you will..
       $scope.something = messageService.message;
   });

这篇关于我怎么可以访问另一个控制器的范围在一个控制器中定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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