Sharing services variables across controllers; Ang

2019-09-04 02:07发布

I have a simple Angular/Ionic app and am trying to share the status of a Boolean variable between two controllers, so different messages in the app are shown depending on if the variable is true or false. At the moment one of the controllers only reads the value initially and is not updated when it is changed.

Here is the controller which is responsible for changing the state of the variable:

.controller('SettingsCtrl', function($scope, Settings) {

  $scope.notifications = Settings.notifications;

  $scope.toggle = function() {
    if (Settings.notifications == false) Settings.switchOnNotifications();
    else Settings.switchOffNotifications();
    $scope.notifications = Settings.notifications;
  };
})

And here is the secondary controller which is only reading the status of the variable:

.controller('HomeCtrl', function($scope, Settings) {
  $scope.notifications = Settings.notifications;
})

Here is the service storing the variable:

.factory('Settings', function() {

  var o = { notifications: false };

  o.switchOnNotifications = function() {
    o.notifications = true;
  };

  o.switchOffNotifications = function() {
    o.notifications = false;
  };

  return o;
})

And here is the html I am trying to update as the variable is changed:

<div ng-hide='notifications'>
  Switch on visit notifications
 </div>

 <div ng-show='notifications'>
   You are due at the gym in:
 </div>

May be something quite straightforward, any help appreciated.

1条回答
看我几分像从前
2楼-- · 2019-09-04 03:01

You're copying the notifications flag from the service into the scope when the controller is instanciated. So, if the flag is modified after that copy is made, the $scope.notifications variable still refers to the value it had when the copy was made.

The simplest way of solving that is to avoid making a copy in the first place, and always refer to the one true value stored in the service:

.controller('HomeCtrl', function($scope, Settings) {
    $scope.settings = Settings;
})

and

<div ng-hide='settings.notifications'>
   Switch on visit notifications
</div>

<div ng-show='settings.notifications'>
   You are due at the gym in:
</div>
查看更多
登录 后发表回答