Subhash Subhash - 17 days ago 6
Javascript Question

Access variable outside controller in angularjs

I want to access or rather use a variable which was modified and initialised in my controller, outside that controller as a regular variable.

here is the controller:

my.app.controller('queryCtrl', ['$scope','$http',function($scope,$http){
var tempAstData={
'rightNode': 'longitude = 72.8604836',
'leftNode': {
'rightNode': 'latitude = 19.1738427',
'leftNode': "fence_brand_name = 'taco'",
'centerOperator': 'AND'
},
'centerOperator': 'AND'
}
// some functions on it
}]);
//normal javascript
// want to use tempAstData here as plain java script in this same file....
//this part is not a controller or anyway related t angular js . This is plane java script.


I am new to angular, any help is appreciated ty.

Answer

As mentioned by @Subhash in a comment in this question he has 3 assync methods in your controller. Then he needs to manipulate your tempAstData variable after this assync methods:

@trichetriche I have 3 asyn methods in my controllers that hits server with POST request. I didn't post it here to avoid complications.To be precise i want to access that tempAstData in my html file with a script tag new Treant(tempAstData)

In this case i suggest to use $q to wait all promises and after this call a method that manipulates tempAstData, like this:

my.app.controller('queryCtrl', ['$scope','$http', '$q',function($scope, $http, $q) {

    var wrapMethod = function (parameter) {
        // do something with parameter
    }

    var tempAstData={
       'rightNode': 'longitude = 72.8604836',
       'leftNode': {
           'rightNode': 'latitude = 19.1738427',
           'leftNode': "fence_brand_name = 'taco'",
           'centerOperator': 'AND'
       },
       'centerOperator': 'AND'
    }

    var promises = [];

    // add promises returned by assync methods to a array
    promises.push(assyncMethod1());
    promises.push(assyncMethod2());
    promises.push(assyncMethod3());


    // wait all promises to be resolved
    $q.all(promises).then(function () {

        // call wrap method with 'normal' JavaScript code previously in a script tag
        wrapMethod(tempAstData);

    })

}]);

@Subhash Please, edit your question and add the complete information to clarify for another users