在控制器之间共享服务的变量;角/离子 [英] Sharing services variables across controllers; Angular/Ionic

查看:95
本文介绍了在控制器之间共享服务的变量;角/离子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的角度/离子应用程序,我试图分享两个控制器之间的布尔变量的状态,在应用程序,所以不同的消息都取决于该变量是真还是假所示。
此刻控制器之一只读取初始值,并且当它被改变不更新

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.

这里是控制器负责改变变量的状态:

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

这里是次级控制器是只读变量的状态:

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

下面是存储变量的服务:

.factory('Settings', function() {

  var o = { notifications: false };

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

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

  return o;
})

这里是我想为变量改为更新HTML:

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

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

可能是一些非常简单,任何帮助AP preciated。

May be something quite straightforward, any help appreciated.

推荐答案

您正在复制通知标记。因此,如果标志被修改,该副本作出后的 $ scope.notifications 变量仍然是指它有当副本做出的价值。

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

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

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

这篇关于在控制器之间共享服务的变量;角/离子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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