Connect the out-of-scope static variable to the HTML in Angular using Typescript

I recently developed a small test website using typescript and angularjs.

Within my project, there is a module that contains a static variable which I would like to connect to the HTML document in order to display the currently logged-in user.

module mytest.constants {

    export class CurrentSession {

        public static CURRENT_USER: string = "Tobi";

    }
}

The issue at hand is that the current scope resides in a controller that is separate from my CurrentSession class.

I am hoping to achieve something like this:

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

An alternative approach could involve adding a class member to the controller and setting it within the constructor like so:

this.CurrentUser = mytest.constants.CurrentSession.CURRENT_USER

However, I would prefer to directly bind the static variable to the HTML file. Is this task feasible?

Answer №1

In order to bind static properties effectively in Angular, you cannot simply reference them directly as the framework does not check them during its digest cycle. However, you can work around this limitation by creating a scope or 'this' reference to the class itself. One way to achieve this is demonstrated below:

module mytest.constants {

    export class CurrentSession {

        public static CURRENT_USER: string = "Tobi";

        CurrentSession = CurrentSession;

    }
}

This code snippet essentially creates its own property using

this.CurrentSession = CurrentSession
.

When utilizing this approach in your template (assuming you are employing the controllerAs syntax with session referring to the controller instance), you will be able to successfully bind to CURRENT_USER like so:

<div>{{session.CurrentSession.CURRENT_USER}}</div>

Answer №2

Appreciation to dfsq for the prompt response.

I managed to discover an alternate solution that worked well for me.

To begin, I created a variable named "CurrentSession" in my app.ts and initialized it with a new instance of my Object

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

Subsequently, I was able to inject this Constant into my controller as shown below:

export class MainCtrl {

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

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

An advantage of this approach is that by using "private CurrentSession" it automatically sets a member-variable "CurrentSession".

This is how the html appears:

<button ng-click="main.logOut()">Log out {{main.CurrentSession.CURRENT_USER.Name}}</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Defining the structure of an object using a type interface

I am having trouble identifying the issue with this type declaration in relation to the interface. https://i.sstatic.net/3dnJk.png When using TypeScript, I encountered an error message stating: "State is an unresolved variable". Does anyone have insight ...

What are some ways to leverage Angular for generating dynamic form fields?

I am looking to display a form based on a dynamic field configuration: $scope.fields = [ { title: 'Label 1', type: 'text', value: 'value1'}, { title: 'Label 2', type: 'textarea', value: 'value ...

The attribute 'id' cannot be found in the class 'Foods'

After examining my code below, I am attempting to remove clients from my data table by using checkboxes. Whenever I check a checkbox, I notice in the console that the object's properties are retrieved from the database. My goal is to delete by id, but ...

Is the TypeScript compiler neglecting the tsconfig.json file?

I am new to TypeScript and currently exploring how to set it up in WebStorm. One of the first steps I took was creating a tsconfig.json file in the main directory of my project and updating the built-in TypeScript compiler to version 1.6.2. However, despit ...

There is no index signature in the type 'string | number | EnvType' that accepts a parameter of type 'string'

Can someone help me troubleshoot this issue with config[curr][targetEnv] ??? interface EnvType { dev: string; staging: string; production: string; } type Config = { [key: string]: number | string | EnvType; }; const config: Config = { network ...

Configuring modules using Sass, CSS-Modules, Webpack, React, and TypeScript

I'm facing an issue with extracting types from my .scss files. I've tried various configurations and solutions, but nothing seems to work. Specifically, my goal is to utilize modules in a React app with TypeScript. Below is my webpack configura ...

Tips for modifying array elements in MongoDB

I have some data stored in a mongoDB database that appears as follows { "_id": ObjectId("57c40e405e62b1f02c445ccc"), "sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"), "notificationDetails": [ { "userId": "57443657ee5b5ccc30c4e6f8", ...

How can I reference a Bootstrap icon in the buttonImage attribute of a jQuery datepicker?

How can I customize the jQuery datepicker button image? I want to use the Bootstrap calendar icon as the button image for the jQuery datepicker. The icon image can be referenced in the HTML page like this: <i class=icon-calendar></i> When us ...

Setting an Angular Directive on a dynamically generated DOM element using Javascript

One of my directives enables the drag-and-drop functionality for DOM elements with the following JavaScript: JS: angular.module('animationApp').directive('myDraggable', ['$document', function($document){return{link: function ...

The ng-if condition is never met

I am currently utilizing AngularJS in my project. <div ng-repeat="l in kites"> <a ng-click="findit(l.green.num)">color</a> <span ng-if="c_{{l.green.num}} == 'y'>kites is </span> </div> Within my c ...

Sending AngularJS routing requests to an Express server

I'm new to AngularJS, Node, and Express. It's been a challenge getting basic routing to work using $http.get or $http.post. The examples I've found online lack clarity on how the filenames, Angular controller path, and server route path shou ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Angular JS is having an issue where the $routeParams object is mysteriously becoming

I've been working on the code Snippet below, but I'm having trouble retrieving values from $routeParams. It seems like $routeProvider is not being called. My goal is to click on a link, retrieve values from URL parameters, and change the page tit ...

Angular CSS: ng-style applied to only one side, the other remains unaffected

I am working on an Angular application that requires a split screen with two halves, each displaying the same array values. The width and height values are set using a service and accessed by a controller. The style is applied using ng-style in the DOM. Ho ...

Establish default values for cascade Select in Angular

My goal is to populate Cascading Select elements with initial values from the model. All models have default values. Here is how the view looks: **1)** <select id="ddN_Universitate" ng-model="CandidatInfo.ID_N_UniversitateAbsolvita" ng-change="N_FACUL ...

Changing the method signature in a TypeScript interface to replace/override the original one

For this specific scenario, the Array<T> interface is being extended in the following manner: interface BetterArray<T> extends Array<T> { push(this: BetterArray<T>, value: T): this; } Important note - the implementation of Arr ...

The deno bundle operation failed due to the absence of the 'getIterator' property on the type 'ReadableStream<R>'

When attempting to run deno with bundle, an error is encountered: error: TS2339 [ERROR]: Property 'getIterator' does not exist on type 'ReadableStream<R>'. return res.readable.getIterator(); ~~~~~~~~~~~ ...

Tips for validating input fields in Ionic to display errors after the user has finished filling them out

*Hello, I'm new to working with AngularJS and I'm currently trying to display an error message after the user has finished typing in the input field. However, I'm encountering an issue where the error message appears as soon as I start typin ...

Leveraging AngularJS ui-router to navigate to a specific state with a unique URL

I am working on an AngularJS application where I need to handle errors by redirecting the user to a 404 state like this: $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ //console.log(unfoundState.to); ...

Can someone share with me the best practices for implementing @HostListener within a method in my Angular 16 project?

Currently, I've been involved in developing a Single Page Application using Angular 16, TypeScript, and The Movie Database (TMDB). My task at hand is to implement the "infinite scroll" functionality on a particular component. To achieve this, I have ...