elpofigisto
elpofigisto

Reputation: 137

Angularjs $rootScope is invisible in controllers

everyone! I'm creating app with authorization. To store user data during session I use such service:

app.service('Session', function ($rootScope, $cookies) {

    var Session = $rootScope.$new();

    Session.createSession = function (accessTo, level, user_data) {

        this.level = level;
        this.accessTo = accessTo;

        if(user_data) {
            $cookies.isAuth = true;
        } else {
             $cookies.isAuth = false;
        }

        this.user = {
            email    : user_data.email,
            fullname : user_data.fullname,
            id       : user_data.id,
            level    : user_data.level
        }

        if(accessTo && accessTo.length == 1 && !$cookies.account) {
            this.account = accessTo[0].id;
            $cookies.account = accessTo[0].id;
        } else {
            this.account = $cookies.account;
        }
    };


    Session.destroy = function () {
        this.level = null;
        this.account = null;
        this.user = null;
        this.isAuth = false;
        $cookies.account = null;
    };

    return Session;
});

In controller use:

Session.createSession(some, params, here);

Afteer that it put some data to rootscope, and i can show it in console, but when i try to see for example Session.user/.level etc. it doesn't work. What is wrong?

Upvotes: 0

Views: 48

Answers (1)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10163

You should be doing this:

app.service('Session', function() {
    // A service is a singleton, as in it a persistent 
    // object you can inject in controllers
    this.foo = 'bar'; // anything on "this" is publicly available

    this.createSession = function() { ... };
    // you can also expose functions that you can call from the controllers 
});

app.controller('Ctrl1', function($scope, Session) {
    // You can inject "Session" here and use stuff you 
    // added on "this" inside of it

    $scope.foo = Session.foo;
    // you can put stuff on the controller's $scope
    // and you can bind to it in your HTML by using <span>{{foo}}</span>

    Session.foo = 'baz';
    // you can change stuff in the service and it will be persisted
});

So now if you navigate to a certain "Ctrl2" that injects "Session" too, Session.foo will be "baz", not the initial "bar" value.

Upvotes: 1

Related Questions