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

Using Node Express.js to access variables from routes declared in separate files

Currently, I am in the process of developing a website with numerous routes. Initially, all the routes were consolidated into one file... In order to enhance clarity, I made the decision to create separate files for each route using the Router module. For ...

Reasons for dividing by 1 in JavaScript

While completing a basic programming assignment from my teacher, I encountered an interesting issue in Javascript. I found that when dividing a number by 1, it returns an unexpected value. Can anyone provide an explanation for this? I have created a jsfidd ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

Lending a hand in deselecting a rule within the jcf-hidden add-on using Selenium

Currently, I am working on automating a website that utilizes the jcf-hidden class (a form of jQuery class) which hides the select element I want to access. By removing the display: block !important; property, I was able to successfully interact with the ...

Functionality of jQuery Mobile Page

$(document).on("pageshow", "#mappage", function (event) { $("#doldur").append("<li> <label onclick='getBina(" + featuressokak[f].attributes.SOKAKID + ");'>" ...

AngularJS validation for mandatory fields is malfunctioning

I made some changes to an angularjs demo starter code and now I'm facing issues with the required field functionality. Even though I can prevent empty submissions, the "required field" error message still appears after a successful submission. Can any ...

Transform the array into an object containing corresponding key-value pairs

In my dataset, I have an array containing various values: [ { "factor": { "data": "f1", "val": [ "val1" ] } }, { "factor": { "data": "f2", "val": [ "val2" ] ...

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

How to Pause or Temporarily Halt in Jquery?

Looking to lift the object up, wait 1000ms, and then hide it. I found this snippet of code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); However, using ".animate({"to ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

Processing requests through Axios and Express using the methods GET, POST, PUT, and DELETE

When working with express router and Axios (as well as many other frameworks/APIs), the use of GET/POST/PUT/DELETE methods is common. Why are these methods specified, and what are their differences? I understand that a GET request is used to retrieve dat ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Declaring Typescript modules across multiple .d.ts files

If my original .d.ts definition file is like this: main.d.ts: declare module myMod { } Now, let's say I want to separate out the security definitions into another file but keep them under the same module. Here's what I'm thinking: main. ...

establishing a connection between an AngularJS application and an ExpressJS backend

I am currently working on developing an application that utilizes AngularJS for the front end and a REST API using Express.js. Both projects were created with Yeoman, with my Angular app running on localhost:9000 and the Express app running on localhost:30 ...

Connect your Nuxt.js application with Mailchimp for seamless integration

I've tried the solution recommended in this thread, but unfortunately, it's not working for me. Every time I run npm run dev, I encounter an error message: ERROR - Compilation failed with 1 error at 11:21:24 The following dependency was not fo ...

Adding a component to a slot in Vue.js 3

My Goal I aim to pass the Component into the designated slot. The Inquiry How can I effectively pass the Component into the slot for proper rendering? It works well with strings or plain HTML inputs. Additional Query If direct passing is not feasible, ...

How can I select just one element to be impacted by a click event when using map in TypeScript?

Currently, I'm facing an issue where I want to change the icon of a button when it's selected. The problem is that using map affects all buttons even if only one is selected. // ... const [clicked, setClicked] = useState(false); <Button sta ...

the buttonclick won't pause the timer

I'm having trouble with the timer function when a button is clicked. The startpause() method sets the start and stop timers, but when I click the button rapidly multiple times, the timer starts to jump by 2-3 seconds. It seems like more than one timer ...

New update to Angular Currency Filter - Now including Symbol Â!

While utilizing angular's currency filter, I noticed an unexpected extra symbol being outputted: Â. This is the HTML code: {{totals.subtotal | currency}} {{totals.tax | currency}} {{totals.total | currency}} The 'totals' object looks lik ...