Stack Exchange
Get the value of a local variable into the controller in AngularJS
I have a JS file containing a controller and other functions structured like this:
class RandomCtrl {
    constructor(randomService) {
    this.randomService = randomService;
    ...
    }

    $onInit() {
        getData.call(null, this);
    }

    ...

}

function getData(RandomCtrl) {
    ...
}


function getChart(data) {
    if (!data) {
        return;
    }

    const chartOptions = getWeekHourlyOptions(data);

    const allCols = [].concat(chartOptions.dataColumns);
    allCols.push(["x"].concat(_.map(chartOptions.xAxis, element => moment(element).valueOf())));
    const xVals = xAxisValues(chartOptions.xAxis);

    ...
}

...

RandomCtrl.$inject = ['randomService'];

export const Random = {
    bindings: {
        data: '<',
        siteNames: '<'
    },
    templateUrl: randomPageHtml,
    controller: RandomCtrl
};

I want to get the value of allCols from getChart() into the Controller.
I've tried to add it in $onInit like this.allCols = getData.allCols but it doesn't work. Probably not the right way.
Any solution to this?

Where are you calling getChart? and why do you need to pass controller to a method?

allCols is a local variable inside that method, I want to be able to use it outside of its method also. The data contained in this variable is  used to populate a chart, a chart can be shown or not if you click somewhere. When the chart must be shown again, I need the data from allCols, that's why I need that information outside getChart()

allCols has type const you can't replace it with a new array/value


Declare allCols as a global variable and populate the data in getChart()
send allCols in getChart() as return value so that whenever this method is called the return value can be stored into another variable and can be consumed

