Eshank Jain
Eshank Jain

Reputation: 179

How can I access my data outside particular scope in Angular JS?

   //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)

Upvotes: 1

Views: 507

Answers (2)

Gregg
Gregg

Reputation: 667

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.

Upvotes: 1

Otacilio Oliveira
Otacilio Oliveira

Reputation: 686

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.

Upvotes: 1

Related Questions