Exchange of service variables between controllers; Angular / Ionic

I have a simple Angular / Ionic application and I am trying to share the status of a boolean variable between two controllers, so different messages are displayed in the application depending on whether the variable is true or false. At the moment, one of the controllers only reads the value initially and is not updated after changing it.

Here is the controller 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 that only reads the status of the variable:

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

      

Here is the service that stores 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 when the variable changes:

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

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

      

Maybe something pretty basic, any help is appreciated.

0


source to share


1 answer


You copy the flag notifications

from the service to the scope when the controller is instantiated. So, if the flag is changed after the copy has been made, the variable $scope.notifications

still refers to the value that it had when copying.

The easiest way to solve this is to avoid copying 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>

      

+2


source







All Articles