1
   //declaring the module
   var app = angular.module("sachin", ["ng-fusioncharts"]);
    //declaring a factory  
    app.factory('team',function(){
    return {
            runs_aus : ''
        };
    });

    app.controller("myCtrl", function($scope,$http,team){
        $scope.australia=[];    
        $scope.total_runs_aus=0;
        //fetching data from JSON
        $http.get("convertcsv.json").then(function(response){
        $scope.sachin_data=response.data;
        angular.forEach($scope.sachin_data, function(value, key){
             // manipulating data
            if (value.opposition=="v Australia"){
            if (value.batting_score=="-"|| value.batting_score == "TDNB" || value.batting_score == "DNB")
                $scope.total_runs=$scope.total_runs;
            else if (value.batting_score.substr(value.batting_score.length - 1) == "*"){
                value.batting_score = value.batting_score.substr(1);
                $scope.total_runs_aus+=parseInt(value.batting_score,10)
            }
            else
                $scope.total_runs_aus+=parseInt(value.batting_score,10);

        });
        $scope.australia.push({ runs:$scope.total_runs_aus});
        team.runs_aus=$scope.total_runs_aus;
        //got final result in $scope.total_runs_aus
        console.log(team.runs_aus);
        //printing inside the scope(works fine)
        });
        console.log(team.runs_aus);
        //printing outside the scope(can't access)
  • I am trying to access the total runs scored outside the then(function()) of the get request

  • first I tried global variables in javascript

  • Now I tried using a factory Any help would be appreciated

4
  • You are working with asynchronous data. Move the logic that uses the totalRuns variable in to the then() function as well. The console logs are being executed before the promise is resolved so the data is not available. Commented Jun 9, 2016 at 18:57
  • Consider using promise chains if you want specific code to execute after the $http.get request is resolved. See an example: stackoverflow.com/a/24360864/5304361 Commented Jun 9, 2016 at 19:04
  • do you understand what I am suggesting? For example, move your console logs underneath the if else block inside the .then() function. The code inside the then() will execute when the $http.get() is done executing. Given the location of your console logs, these are executed before the data is available. Commented Jun 9, 2016 at 22:36
  • can promise chaining be used? I am adding another .then(console.log("test")); after the first http.get("url").then(#code).then(console.log("test")); but doesn't work for me Commented Jun 10, 2016 at 14:24

2 Answers 2

1

You can use a service to store that data:

app.service('MyService', function() {

    var self = {
        'myString': 1,
        'myObject': {},
        'myArray': [],
        'doSomething': function(param) {
            self.myString = param
        },
        'anotherFunction': function() {
            return true;
        }
    }

    return self;

});

You just need to inject MyService on your controller and access it like MyService.myObject = something.

Sign up to request clarification or add additional context in comments.

1 Comment

This is not going to work because it has nothing to do with Asynchronous operations.
1

The important part to understand is that you are working async operations. The code continues to execute and prints your console logs even though the data has not been returned from $http.get(). Your code needs to account for this and run the code that operates on the data after its been resolved.

.then() expects a function as the parameter of the method signature. For example:

$http.get("convertcsv.json").then(function(response){
    $scope.sachin_data=response.data;
}).then(function() {
    console.log('Value in scope:', $scope.sachin_data);
});

or

function processData = function() {
    console.log('Value in scope:', $scope.sachin_data);
};

$http.get("convertcsv.json").then(function(response){
    $scope.sachin_data=response.data;
}).then(processData);

or chain multiple promises together (you must add angular's $q as a dependency):

function processData1 = function(data) {

    //Create a deferred object.
    var defer = $q.defer();

    //Do something with data.
    console.log('Value in scope:', data);

    //Pass data to next promise in promise chain.
    defer.resolve(data);

    //Resolve data to be returned.
    return defer.promise;
};

function processData2 = function(data) {

    //Create a deferred object.
    var defer = $q.defer();

    //Do something else with data.
    console.log('Value in scope:', data);

    //Pass data to next promise in promise chain.
    defer.resolve(data);

    //Resolve data to be returned.
    return defer.promise;
};



$http.get("convertcsv.json")
     .then(processData1)
     .then(processData2);

Please have a look at:

The code as is may have syntax errors as it has not been tested. Links are general reference and not specific to $q but the concepts are consistent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.