I'm perplexed as to why my array remains empty despite assigning a value to it in my controller. (Just to clarify, I am working with AngularJS, not Angular)

I spent a whole day debugging this issue without any luck.

Issue:

this.gridOptions.data = this.allTemplatesFromClassificationRepo ;
**this.allTemplatesFromClassificationRepo ** remains an empty array. I have already called the activate() function to assign an array to **this.allTemplatesFromClassificationRepo ** before this line of code runs. Please refer to this line
this.allTemplatesFromClassificationRepo = templateReorderProperties;

P.S. Even though I cannot fetch the value of

allTemplatesFromClassificationRepo
in the controller, I can access its value in the html.

namespace app.admin {
'use strict';

class FooController {
    static $inject: Array<string> = [];

    constructor() {
        this.activate();
    }

    activate() {
        this.getData();

        this.classificationFoo = this.data[0];

        this.getTemplateFromGivenRepo(this.classificationFoo.id, this.classificationFoo.displayName);

        this.populateData();
    }

    data: any;

    classificationFoo: any;

    allDataFromclassificationFoo: any = [];

    // demo grid
    gridOptions = {
        enableFiltering: true,
        },
        data: []
    };

    populateData() {
            this.gridOptions.data = this.allTemplatesFromClassificationRepo ;
    }

    getData() {
        this.fooService.getUserData();
        this.data = this.fooService.userdata;
    }

    getTemplateFromGivenRepo(fooId: string, fooName: string) {
        switch (fooId) {
            case 'FOO':
                this.TemplateApi.templatesAvaiableForRepoIdGET(fooId).then(data => {
                    data.forEach(element => {
                       element.fooName = fooName;
                    });

                    let templateReorderProperties = data

                    this.allTemplatesFromClassificationRepo = templateReorderProperties;
                }, error => {

                });
                break;

            default:
                break;
        }
    };
}

class Bar implements ng.IDirective {
    static $inject: Array<string> = [];

    constructor() {
    }

    bindToController: boolean = true;
    controller = FooController;
    controllerAs: string = 'vm';
    templateUrl: string = 'app/foo.html';

    static instance(): ng.IDirective {
        return new Bar();
    }
}

angular
    .module('app.admin')
    .directive('bar', Bar.instance);

}

Answer №1

fetchTemplateFromSelectedRepository
is an asynchronous operation.

Ensure that the this.populateGridData(); method is called inside the

fetchTemplateFromSelectedRepository
function after

this.allTemplatesFromClassificationRepo = templatesOrderedByProperty;

fetchTemplateFromSelectedRepository(repoId: string, repoName: string) {
            switch (repoId) {
                case 'CLASSIFICATION':
                    this.TemplateApi.getTemplatesForRepository(repoId).then(data => {

                        this.allTemplatesFromClassificationRepo = templatesOrderedByProperty;
                        this.populateGridData(); // call at this point
                    }, error => {

                    });
            }
        };

OR

You have the option to return a promise from

fetchTemplateFromSelectedRepository
and then in the then method's success callback, execute this.populateGridData();

Answer №2

It seems like the issue lies within this specific instance that changes inside a Promise resolve.

To address this, consider adding the following at the beginning:

var self = this;

Afterwards, replace all instances of this with self.

For example:

self.gridOptions.data = self.allTemplatesFromClassificationRepo;

// continue updating references to self ...

This will ensure that you are consistently using the same scope instance.


Fingers crossed that this solution solves the problem!

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

Troubleshooting: AngularJS View Fails to Update with Defer and Factory

I've encountered an issue where my view doesn't update when I create a new setting without refreshing the page. Can someone provide guidance on how to resolve this issue? If there's a better approach to achieving this, please share that as w ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Prevent the selection of a dropdown option in AngularJS once it has already

var demoApp = angular.module('myApp', []); demoApp.controller('QaController', function($scope, $http) { $scope.loopData = [{}, {}]; $scope.questions = { model: null, availableOptions: [ {id: '1& ...

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

How can I access the data stored in this $scope?

I am currently working on integrating text-to-speech features into my chatting application. In order to achieve this, I need to extract the message value from the $scope.messages object without including other data such as from, fromname, to, and time. $s ...

What is the most efficient way to transfer a large search results array between NodeJS and AngularJS?

My application is built with NodeJS for the back-end and AngularJS for the front-end. I've run into an issue where sending a search query from Angular's $http to the back-end results in a bottleneck when there is a slow internet connection. Angul ...

Leverage scope Variable in Angular Service URL

Currently, I am aiming to retrieve data from an API by sending specific search parameters through an AngularJS service. Within my ng-model, I have a variable named "search" that I want to utilize as a parameter in the API URL. My initial (unsuccessful) at ...

Unexpected errors are encountered when using ng serve

When I run the ng serve command, unexpected errors are occurring on my system. The errors include: PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0 ...

Is there a way to reset an AngularJS controller to its initial state after a data change?

I have been trying to understand the API documentation for this, but it seems a bit challenging. Let's say I have a controller that retrieves data on its initial call: myCtrl = function ($scope, Data) { $scope.data = []; data_promise = Data.getD ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...

Angular removing every query string parameters

Linked to but distinct from: How to maintain query string parameters in URL when accessing a route of an Angular 2 app? I am facing an issue with my basic Angular application where adding a query parameter results in its removal, both from the browser&apo ...

Guidance on toggling elements visibility using Session Service in AngularJS

After reading this response, I attempted to create two directives that would control the visibility of elements for the user. angular.module('app.directives').directive('deny', ['SessionTool', function (SessionTool) { ret ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Pass the DateTime object from ASP.NET to angularjs as a structured data type instead of converting it to a

I'm encountering an issue where I am sending a complex object from my ASP.NET backend to the AngularJS frontend. This object includes a DateTime property and a list of objects, each with their own DateTime property. These properties are all sent as st ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Can you identify the nature of the argument(s) used in a styled-component?

Utilizing typescript and react in this scenario. Fetching my variable const style = 'display: inline-block;' Constructing a simple component export const GitHubIcon = () => <i className="fa-brands fa-github"></i> Enh ...

Utilizing TypeScript for dynamic invocation of chalk

In my TypeScript code, I am trying to dynamically call the chalk method. Here is an example of what I have: import chalk from 'chalk'; const color: string = "red"; const message: string = "My Title"; const light: boolean = fa ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Elusive Essence: Mysterious Origins of the

Beginner in the world of Ionic and Angular. I am attempting to create a test app and incorporating the factory function. I obtained the design from Ionic Creator and now trying to add my code to it. Here is my controller file. angular.module('app.c ...