Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind static variable (out of scope) to html in Angular / typescript

I created a little test typescript/angularjs website.

I have this module with a static variable which I want to bind to the html-document so that I can see the current logged-in user.

module mytest.constants {

    export class CurrentSession {

        public static CURRENT_USER: string = "Tobi";

    }
}

the problem is: the current scope is a controller which is separated from my CurrentSession-class.

I would like to do something like

<div class="label" style="color:green">
  Logged in as: {{mytest.constants.CurrentSession.CURRENT_USER}}
</div>

Another way I could do is to add a class-member to the controller and set it in constructor like:

this.CurrentUSer = mytest.constants.CurrentSession.CURRENT_USER

but I would prefer to bind the static-variable directly to the html-file.

is this possible?

like image 386
Tobias Koller Avatar asked Jul 18 '15 09:07

Tobias Koller


2 Answers

You can't bind static properties like this, Angular just doesn't check those in its digest cycle. You can however create a scope/this reference to the class itself. Something like this:

module mytest.constants {

    export class CurrentSession {

        public static CURRENT_USER: string = "Tobi";

        CurrentSession = CurrentSession;

    }
}

So basically it will create own property like this.CurrentSession = CurrentSession.

Then in template (assuming you are using controllerAs syntax with session refer to controller instance) you would be able to bind CURRENT_USER as

<div>{{session.CurrentSession.CURRENT_USER}}</div>
like image 183
dfsq Avatar answered Nov 02 '22 02:11

dfsq


thank you dfsq for your quick answer.

I finally found another solution.

I first set a variable called "CurrentSession" in my app.ts and set the value to a new Instance of my Object

angular.module("app", [])
    .constant("CurrentSession", new mytest.constants.CurrentSession())

then I can just inject this Constant in my controller like this:

export class MainCtrl {

    public static $inject = ["$state", "$http", "CurrentSession"];

    constructor($state, $http, private CurrentSession) {
      ...
    }

the good thing here is, that I can use the "private CurrentSession" which will automatically set the a member-variable "CurrentSession".

The html looks like this:

<button ng-click="main.logOut()">Log out {{main.CurrentSession.CURRENT_USER.Name}}</button>
like image 22
Tobias Koller Avatar answered Nov 02 '22 02:11

Tobias Koller