5

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?

2 Answers 2

6

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.