Angularjs and Meteor “Session” reactivity, is there a way?

青春壹個敷衍的年華 提交于 2019-12-04 07:30:38
Urigo

this as an old question with old answers but I see people referring to it so here is the updated answer.

First - there is a new library for angular-meteor that handles those cases for you.

And this library gives you two possible solutions:

  1. If you want to bind a Session variable to a scope variable, use the $meteorSession service. What it does is that every time the scope variable will change, it will change to Session variable (and trigger an autorun if it's placed inside one). and every time the Session variable will change, the scope variable will change as well (and change the view that it's placed upon).

  2. If you are using the Session variable just to get a variable reactive (meaning trigger an autorun), you should use getReactively . this just returns the already existing scope variable but trigger an autorun every time it changes. a good example of this can be found it our tutorial.

    • Note: In anyway, when you use Tracker.autorun inside Angular, you need to connect it to a scope. this can be easily done if you replace Tracker.autorun with the $meteorUtils autorun function

Hi here is an option (might not be the best but it works I think)

app.service('Session',function($rootScope){
    var self = this;
    self.objects = {};
    self.get = function(name){
            self.objects[name] = {"value" : Session.get(name)};
            Meteor.autorun(function() {
                    var i = Session.get(name);
                    if(self.objects[name].value != i){
                            if (!$rootScope.$$phase){
                                    $rootScope.$apply(function(){
                                            self.objects[name].value = i;
                                    });
                            }
                    }
            });
            return self.objects[name];
        }
        self.set = function(name,value){
            self.objects[name].value  = value;
            Session.set(name,value);
        }
        return self;
});

Call it in the $scope like this $scope.test = Session.get("test");

In the view as {{test.value}}. Sorry for the late answer .

Happy new year!

try

angular.module('yourmod', [])
.controller('TestCtrl', ['$scope', function($scope) {
  var c = Deps.autorun(function (comp) {
     //... put reactive stuf on scope.....
     if(!comp.firstRun) {
       // only do not do aply at first run becaulse then apply is already running.
       $scope.$apply()
     }
  });

  // and to realy make it nice...
  $scope.on('$destroy', function () {c.stop()});
}])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!