Search code examples
angularjsvariablesscopeangularjs-scopelocal-storage

AngularJS: How to access variable from inside a promise and use within the controller?


I'm trying to declare an array inside a function of a controller that happens after the factory pulls for data, and then access it after the function is done being completed. Here's what I have for my code:

app.controller('SignUpController', function ($scope, $http, $location, DailyCounterService, $localStorage) {

    DailyCounterService.GetDailyCountersList().then(function (d) {
        $scope.DailyCounters = d.data;
        $scope.allCounters = [];

        var daySixteen = d.data.filter(function (d) {
            // This is where I'm building the array I want to access later
            $scope.allCounters.push(d.MICounter);

            return d.MIDay === "16";
        });

        console.log($scope.allCounters);
        // This prints in console '[2, 6, 1, 1, 7, 8, 2......]'
        // So the array is now initialized

    }, function (error) {
        alert('Error!');
    });

    // Here is where I want to access $scope.allCounters once again
    // But Can't because doing this:
    console.log($scope.allCounters);
    // prints 'undefined'
    // How would I make $scope.allCounters be able to be accessed here?
})
.factory('DailyCounterService', function ($http) {
    var fac = {};
    fac.GetDailyCountersList = function () {
        return $http.get('/Data/GetDailyCountersList')
    }
    return fac;
})

As I've asked in the comments towards the end of my controller, how would I be able to access the variable set in the function prior outside of that function?


Solution

  • Well, if this controller is associated with a route, then you can tie up this get code in the resolve attribute of the route provider like this,

    .when("/signup", {
        templateUrl: "signup.html",
        controller: "SignUpController",
        resolve: {
            allCounters: 
            function(DailyCounterService){
                DailyCounterService.GetDailyCountersList().then(function (d) {
                 // Do your stuff
                 return allCounters;
            }, function (error) {
                 alert('Error!');
             });
            }
        } 
    }),
    

    and access allCounters in you controller like this,

     app.controller('SignUpController', function ($scope, $http, $location, allCounters, DailyCounterService, $localStorage)
    

    By this way all counters will always be initialized when your controller is loaded.

    More on resolve: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx