How to access a TypeScript global variable from outside an Angular controller?

In my main.ts file, there is a global variable named rowTag which is an array of Tag[] entities.

Additionally, I have an angular controller named TagMeController.ts.

Below is the constructor of TagMeController:

constructor($scope, $rootScope) {
            $scope.CloseMe = this.CloseMe;
            $scope.rowTags = rowTag; // referring to the global variable
            $scope.colTags = colTag; // another global variable
            $scope.UpdateMe = this.UpdateMe;
        }

When I update the rowTag object from the same controller, the changes are reflected in the UI. However, if I update the same object from a different .ts file (main.ts), the changes are not reflected.

Any suggestions on how to make this variable observable?

Answer №1

Is there a way to make that particular variable observable?

One solution is to create an angular service to store that specific piece of information,

class Tags {
    rowTags = [] 
    colTags = []
}

Then, incorporate the service like this:

constructor($scope, $rootScope, tags: Tags) {
    $scope.CloseMe = this.CloseMe;
    $scope.tags = tags; // Tags service that holds `rowTag` and `colTag`
    $scope.UpdateMe = this.UpdateMe;
}

For a guide on creating an angular service with TypeScript, check out this helpful video: https://www.youtube.com/watch?v=Yis8m3BdnEM

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

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

The select dropdown does not automatically refresh when the array value changes

I am facing an issue with a select dropdown that is populated by an array filled with data from the server response: myApp.controller('mController', function($scope, $routeParams, $http, contextRoot) { var dataObject = {} $scope.arr = [ ...

Adding a new property to the Express request object type: what you need to know

Recently, I developed a custom middleware that executes specific logic tasks. It operates by transforming the keys to values and vice versa within the req.body. Both the keys and values are strings, with built-in validation measures in place for safety. T ...

The distinction lies in whether the function is called directly within the ng-click attribute or is delayed until after the DOM has

Having an issue with AngularJS, I wanted to inquire about the difference between these two methods: angular.element(document).ready(function () { $scope.callFunction(); }); and <a href="#" ng-click="callFunction()"></a> When modifying a ...

Oops! ExcelJs is throwing an error: "Unable to merge cells that are already

Currently, I'm attempting to create an Excel sheet using excelJs. Each order has an array of order items, which could be one or more. My goal is to avoid repeating certain information within the order while iterating through each item in the order. Ho ...

A versatile function capable of invoking two APIs simultaneously, with one of them being designed to return an array

Here is the code snippet that I am working with: getElements(apiUrl: string): Observable<Element[]> { return this.httpClient.get<any>(apiUrl + 'test/elements').pipe( catchError(error => { if(error.status === ...

The perfect pairing: Visual Studio and Gulp

Having trouble running Gulp in Visual Studio for an angular app, I encountered the following error message: Cannot evaluate the item metadata "%(FullPath)". The item metadata "%(FullPath)" cannot be applied to the path "node_modules\gulp\node_m ...

Click the toggle ng-press attribute

I have a section with an on-click="..." action. The event slightly adjusts the section's appearance within the document so that it resembles a button. I am looking to switch between making this section clickable and non-clickable in my program. While ...

Having trouble retrieving data from a json file using a GET request in Angular?

As a novice in dealing with json objects, I am having trouble extracting data from the GroupResult object. Below is the structure of my classes: export class GroupResult { Id!: number; Lecturer!: string; GroupName!: string; Subjects!: SubjectStats ...

The attribute specified is not present on the element within the array

I'm attempting to create an array that includes an object with initialized properties and a number. Yet, I encounter this error message: The error states: 'Property 'foo' does not exist on type 'number | IObj'. The proper ...

Can default values be assigned to a DTO during initialization?

What is the method to assign default values when a query is empty? In the case where I have this DTO structure for a query: export class MyQuery { readonly myQueryItem: string; } If the request doesn't include any query, then myQuery.myQueryItem ...

Troubleshooting Problem: Difficulty with Uploading High-Resolution Images in Angular using

Currently, I am working on implementing file uploads using the combination of express.js, node, and angular. Everything seems to be functioning well when dealing with small image files. However, I encountered a 404 error when attempting to upload larger im ...

Using AngularJS for AJAX operations with dynamic PHP variables

I have an AngularJS code that is looping through an AJAX JSON response like this: <div ng-repeat="post in posts"> {{post.title}} {{post.url}} </div> It's working fine. How can I pass a PHP variable based on the JSON? Let's assume t ...

Prevent external scrolling while Bootstrap modal is active

<div class="modal mt-5p" role="dialog" [ngStyle]="{'display':IONotes}"> <div class="modal-dialog modal-md mt-0px width-70p"> <div class="modal-content" style="height:500 ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

AngularJS/Bootstrap: Tips for keeping accordion-heading at the top during scrolling

I am working with a directive that contains an angularjs accordion list. Each section in the accordion-body has lengthy content. The issue I am facing is that when I expand an item and scroll down to view all the content, the header of the item goes out of ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

When using ng-repeat with an array, not all array values are repeated

I have a basic angular block that looks like this <script> function simpleList($scope){ $scope.addItem = function(){ $scope.items.push($scope.newItem); } $scope.items = ["apple", " ...