如何从另一个控制器的范围访问一个控制器中定义的变量? [英] how can I access a variable defined in one controller from the scope of another controller?

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

问题描述

我有以下控制器:HeaderCtrlNewsFeedCtrlMainCtrl

MainCtrl 包含其他两个控制器,它们在同一级别.

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

我在 authenticationService 中定义一个对象并在 MainCtrl 中更新它的值,我在 NewsFeedCtrl 中经常更新它,我想显示它在 HeaderCtrl 控制的 HTML 页面中的值.

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 中使用这一行时:

when I use this line in my 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天全站免登陆