Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so:

function MyDirective(): ng.IDirective {
    var directive = <ng.IDirective>{
        restrict: "E",
        template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGridOptions" class="ag-fresh ag-basic"></div>',
        scope: { gridOptions: '=', rowClicked: "&", api: '=' },
        controller: gridController,
        controllerAs: 'vm',
        bindToController: true
    }
    return directive;
}
angular.module("angularWithTS").directive("myDirective", MyDirective);

This is the structure of my controller class:

 export class gridController {
    public agGridOptions: any = {};
    public api: any = {};
    public gridOptions: any;
    public rowClicked: any;
    constructor() {
        this.initialize();
    }
    private initialize() {
        /*****Contoller Logic*****/
        var columnDefs = commonFunctions.convertToAgColumns(this.gridOptions.columnDefinitions);

        this.agGridOptions.enableSorting = true;
        this.agGridOptions.editable = true;
        this.agGridOptions.enableColResize = true;
        this.agGridOptions.columnDefs = columnDefs;
        /*****Contoller Logic*****/

        /*****Exposed Events*****/
        this.agGridOptions.onRowClicked = function (event) {
            this.rowClicked({ index: event.rowIndex });
        };
        /*****Exposed Events*****/


        /*****Public Api*****/
        this.api = {
            populateData: function (options) {
                this.agGridOptions.api.setRowData(options.rowData);
            }
        }
    }
    /*****Public Api*****/
}

The directive tag in HTML is structured as follows:

<my-directive grid-options="options" api="gridApi"></my-directive>

My question pertains to an issue where the variable `agGridOptions` becomes undefined when calling the public API method `populateData()` in the controller. Why is `agGridOptions` unavailable when invoking the public API? Any assistance would be greatly appreciated.

The method call in the controller is made in the following manner:

     $scope.gridApi = {};
  $scope.options = {};
            $scope.options.columnDefinitions = $scope.columnDefinitions;
    $http.get("monthlySales.json").then(function (response) {
        $timeout(function () {          
            $scope.options.rowData = response.data;
            $scope.gridApi.populateData($scope.options);
        },2000);
    });    

Initially, when the controller is invoked, all variables such as `gridOptions` and `agGridOptions` hold their respective values correctly. However, `agGridOptions` becomes undefined when calling the `populateData()` API to display retrieved data.

Answer №1

The function 'this' you are referencing in your code is actually pointing to the function itself, not your controller-

this.api = {
        populateData: function (options) {
            this.agGridOptions.api.setRowData(options.rowData); //(this = populateData function)
        }
    }

To resolve this issue, you can change the syntax to use arrow functions () => so that the typescript compiler will automatically handle the 'this' context by transforming it into _this in the javascript file.

Here is how the updated code should look:

this.api.populateData =  (options)=> {
            this.agGridOptions.api.setRowData(options.rowData);    
    }

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

Guide on utilizing $q for retrieving a promise from a $broadcast within angularJS

Currently, the controller code I've written is structured like so: $scope.spAPI.load(id).then(function(result){ var deferred = $q.defer(); if(result !== undefined){ deferred.resolve($rootScope.$broadcast("onSpLoaded", result)); } return de ...

Using Firebase: retrieving getAdditionalUserInfo in onCreate of a Firebase Cloud function

Can anyone help me figure out how to retrieve extra data from a SAML login provider in the backend (firebase functions)? I can see the data on the client side but I'm struggling to access it in the backend. I've specified these dependencies for ...

Avoiding model updates when cancelling in angular-xeditable

I am utilizing angular-xeditable. When changing the value of "editable-text" and pressing the Cancel button, the "editable-text" value should revert back to its previous one. In other words, "editable-text" keeps updating the model even if the Cancel butto ...

How can state values be transferred between components?

I have come across various answers on different platforms but haven't been able to achieve the desired results. That's why I am reaching out with this question. So, my question is related to 3 files named: App.js, SignUp.js, and Welcome.js. My ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

Submitting the object in the correct format for the Firebase database

My goal is to structure the Firebase database in the following way: "thumbnails": { "72": "http://url.to.72px.thumbnail", "144": "http://url.to.144px.thumbnail" } However, I am struggling to correctly set the keys '72' and '144&apos ...

Encountering a syntax issue with pipeable operators in Angular Rxjs

I am currently in the process of rewriting this code snippet: Observable .merge(this.searchQuery$, this.lazyQuery$) .do(() => this.loadingPage()) .map(filter => this.buildURL("jaume", Config.security['appName'], filter)) .s ...

Making HTTP requests to the Gmail API

Today, I dedicated most of my time to learning how to utilize the Gmail API with node.js. Following Google's QuickStart guide, I successfully got the API up and running fairly quickly. It seemed like there were two methods for making API requests. One ...

invoke the next function a different privateFunction within rxjs

I'm trying to figure out how to pass the resetPassword data to the _confirmToUnlock method in Typescript/RxJS. Here is my subscribe method: public invokeUnlockModal() { let resetPassword = { userName: this.user?.userName}; //i need to send this ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...

Forge: Securely encrypting massive files

I rely on the forge framework for implementing PGP functionality, specifically for encrypting large files (2gb or larger) while minimizing RAM usage. What would be the most efficient approach to achieve this? ...

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

How Web Components interact with innerHTML within connectedCallBack

class Form extends HTMLElement { constructor() { super() } connectedCallback() { console.log(this) console.log(this.innerHTML) } } customElements.define("my-form", Form); I'm currently faci ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Sending information into MySQL using NodeJS with the help of Postman

As a newcomer in the field, I am exploring how to combine MySQL with nodeJS for integrating projects into WordPress. app.post('/users/add', (req, res) => { id = req.body.id, firstname = req.body.firstname, surname = req.body.surname ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

Leveraging angular-cli built files as a dependency for another angular2 project

Is it feasible to utilize the build artifacts from one angular-cli project in another? For instance, I have created and published project "A", then subsequently created project "B" and added A to its dependencies (node_modules). Currently, these are the ...

Is the issue with AJAX and a global variable a result of my misunderstanding?

My goal is to use AJAX to load client data onto a page and then replace a company ID with the corresponding name from a different company table in the same database. However, I am facing an issue where the global JavaScript variable is not being updated wi ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...