how can I access a variable defined in one control

2019-08-26 09:06发布

问题:

I have the following controllers: HeaderCtrl, NewsFeedCtrl, MainCtrl

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

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.

when I use this line in my HeaderCtrl:

$scope.unreadNum=authenticationService.notificationList.length;

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

{{unreadNum}}

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.

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.

回答1:

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